How to construct C struct in Go side?

1k views Asked by At

I need to call a C function which needs a pointer of struct as argument. Here's the C code:

struct Position
{
    uint64_t index;
    uint64_t offset;
};

int read(const char* filename, const Position* pos, const char** data)

So in Go code, I think I have to malloc memory to construct a Position object and pass its pointer to C function. Maybe I also need to free memory. It seems like what C.CString() did. So how can I do that? Is there any code example? THX.

1

There are 1 answers

2
Jiang YD On

How call c from golang is clear by the generated stub. use go build -work src/main.go to generate the stub and get the working directory. find the function prototype in _obj/_cgo_gotypes.go file. i.e. I can get the following generated go stub:

type _Ctype_Position _Ctype_struct__Position
type _Ctype_struct__Position struct {
//line :1                                                                                                                                                                                                           
    index   _Ctype_int
//line :1                                                                                                                                                                                                           
    offset  _Ctype_int
//line :1                                                                                                                                                                                                           
}
func _Cfunc_read(p0 *_Ctype_char, p1 *_Ctype_struct__Position, p2 **_Ctype_char) (r1 _Ctype_int)

if i have the c header file like this:

typedef struct _Position
{
  int index;
  int offset;
}Position;

extern int read(const char* filename, const Position* pos, const char** data);

BTW you need reference the c function in go source to make a dependency for go build to generate the referenced function stub.