I want to call a go function from C++ and return a string.
The function:
//export EditStr
func EditStr(a string) (ostr string) {
ostr = fmt.Sprintf("[["+a+"]]")
fmt.Println(">> " + ostr)
return
}
CGO seems happy to compile this and generates:
extern GoString EditStr(GoString a);
When calling the function from C++
auto res = EditStr(GoString{.p = "asdf", .n = 4});
My debug output works (so passing the string to go seems fine), but it fails when returning the string.
>> [[asdf]]
panic: runtime error: cgo result is unpinned Go pointer or points to unpinned Go pointer
The documentation (https://pkg.go.dev/cmd/cgo#hdr-C_references_to_Go) seems to imply GoString works for passing data into go but does not really say anything about returning it.
The example MyFunction2 seems to hint *C.char should be used to return strings, but CGO seems to be happy returning string directly.
Is this just a bug / missing warning / missing error in CGO or is there a way to return strings directly?
(I know I could use (int64, *C.char) as a return value, but it seems silly to manually return the values if there is the GoString struct seeming to be intended to package those values.)
_GoString_); this is only useful for passing string values from Go to C and back to Go”. You need to return a type that you can use in C._GoString_type also may not be pinned withruntime.Pinner. Because it includes a Go pointer, the memory it points to is only pinned for the duration of the call;_GoString_values may not be retained by C code."._GoString_back to GO, since I get a runtime error before I am able to do this. Thus I can't even treat it as an opaque handle which I can only pass back to GO.