For the work that I am doing to integrate with an existing library, I had to write additional C code to provide an interface that could be used through CGo.
To avoid redundant copies of the data, I would like to be able to pass some standard Go types (like Go strings) to these C adapter functions.
I see that there are GoString and GoInterface types defined in the CGo header that are created for use by exported Go functions, but is there a way to use these types in my own prototypes of functions that CGo recognizes?
Currently, I used void * in C prototypes and passed unsafe.Pointer(&value) on the Go side. This is less clean than we would like (first, it gives C-code the ability to write a value).
Update:
Just to be clear, I know the difference between the original string type of Go and C char * . I want to say that since I will copy the string data passed to my C function, it doesn’t make sense in any case for the Go side code to make its own copy.
I also understand that the layout of the string may change in a future version of Go, and its size may vary by platform. But CGo already reveals type definitions that match the current platform for me through the documented header _cgo_export.h that it creates for me, so it seems a little strange to say that it is not defined:
typedef struct { char *p; int n; } GoString;
But there seems to be no way to use this definition in prototypes visible to CGo. I'm not too worried about binary compatibility, since the code using this definition will be part of my Go package, so it will be enough for compatibility with the source level (and there would be no big deal to upgrade the package if it wasn’t).
source share