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
", 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
", 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
", message)
Is there a simpler way?