0

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.

Meng
  • 747
  • 1
  • 6
  • 5

1 Answers1

-2

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.

Jiang YD
  • 3,205
  • 1
  • 14
  • 20
  • 1
    This answer doesn't explain how to allocate a new `struct Position` value that can be used with the imported `read` function. – Dai May 16 '18 at 07:33
  • that's true. You need know basics cgo inter-calls. Then my answer will fill the gap of alloc and pass struct. – Jiang YD May 16 '18 at 09:29