I'm trying to call a C function from Go with cgo to read an error message. The function produces a message of an unknown length less than 256 bytes.
Working example in C:
char message[ERROR_SIZE]; //256
last_error( message, sizeof(message) );
printf( "message: %s\n", message );
My attempt in Go (not working):
var ptr *C.char
C.last_error(ptr, ERROR_SIZE)
var message = C.GoString(ptr)
fmt.Printf("message: %s\n", message)
When the go code is run, the message is empty. Does the go version need to preallocate space for the message? How to do this?
Update after comment by LPs to pass an array. This works, but seems a bit awkward:
var buf [ERROR_SIZE]byte
var ptr = (*C.char)(unsafe.Pointer(&buf[0]))
C.last_error(ptr, len(buf))
var message = C.GoString(ptr)
fmt.Printf("message: %s\n", message)
Is there a simpler way?
C.GoStringallocates space as necessary, and it should work in this instance whenever you have a null terminated string. If The string isn't null terminated, or may contain null characters, just treat it as bytes, and useC.GoBytes.