I am trying to copy content of structure in GO
type test struct {
a string
b string
}
to C structure.
typedef struct {
char a[10];
char b[75];
}test_c;
My requirement does not allow me to change the structure of member types of both GO and C. I have written the following code, to copy GO structure to C structure, and i am able to copy them too.
cmain.h
typedef struct {
char a[10];
char b[75];
}test_c;
void cmain(test_c* value);
cmain.c
#include <stdio.h>
#include "cmain.h"
#include "_cgo_export.h"
void cmain(test_c *value) {
printf("Inside C code\n");
printf("C code structure Member:a=%s\n", value->a);
printf("C code structure Member:b=%s\n", value->b);
}
go_func.go
package main
import (
/*
#include "cmain.h"
*/
"C"
"fmt"
"unsafe"
)
type test struct {
a string
b string
}
func main() {
var p_go test
var p_c C.test_c
p_go.a = "ABCDEFGHIJ"
p_go.b = "QRSTUVXWYZ"
fmt.Println(unsafe.Sizeof(p_c.a))
StructMemberCopy(&p_c.a, p_go.a)
fmt.Println("In GO code\n")
fmt.Println("GO code structure Member:a=%s", p_go.a)
fmt.Println("GO code structure Member:b=%s", p_go.b)
fmt.Println("Call C function by passing GO structure\n")
C.cmain((*C.test_c)(unsafe.Pointer(&p_c)))
}
func StructMemberCopy(dest *[10]C.char, src string) {
for i, _ := range src {
dest[i] = C.char(src[i])
fmt.Printf("%d %c \n", i, src[i])
}
}
Here am trying to write a generalized function to copy the content of GO Structure member to C Structure
func StructMemberCopy(dest *[10]C.char, src string) {
for i, _ := range src {
dest[i] = C.char(src[i])
fmt.Printf("%d %c \n", i, src[i])
}
}
In the above code, when i call the function StructMemberCopy(&p_c.a, p_go.a), with &p_c.a as argument the code compiles without any error, but when i send &p_c.b, it gives an error
cannot use &p_c.b (type *[75]C.char) as type *[10]C.char in argument to StructMemberCopy
Can anyone give some inputs as to how to write the generalized argument for func StructMemberCopy, as my C Structure array member size can vary. How the first argument for func StructMemberCopy be so that it can take array of different size. . Mean it can become
typedef struct {
char a[10];
char b[75];
}test_c;
or typedef struct {
char a[15];
char b[40];
}test_c;