Just pass the null-terminated string and use C.int(len(goString)) as the length. The length of a Go string is already in bytes and does not include the terminating null (since Go has none), and I assume C.CString() produces the same byte sequence without encoding conversions.
> On Oct 31, 2016, at 10:23 AM, Peter Mogensen <a...@one.com> wrote: > > Hi, > > I was trying to find the official way to pass a Go string to CGO code as a > void* (or char*) with explicit length. > ... using only one allocation/copy. > > I could probably just call C.CString(string) and ignore the extra \0 added by > CGO, but I'm a little puzzled that there's not a shorthand for those with C > APIs not using null-terminated strings. > > Someone proposed this hack: > > *((**byte)(unsafe.Pointer(&theString))) > > ... resulting in a *byte pointing to the data - which can then be copied to > C-managed memory. > > But that relies on knowing that the string implementation starts with a > pointer to the data. > > It would be great with a > > func C.CStringData(string) (*C.char, C.int) // or void* > > /Peter > > > -- > You received this message because you are subscribed to the Google Groups > "golang-nuts" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to golang-nuts+unsubscr...@googlegroups.com. > For more options, visit https://groups.google.com/d/optout. > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.