I'm trying to use a C library in Go. The C.PrlFoundVmInfo_GetName
function writes a UTF-8 encoded string into name with length nBufSize.
// PRL_CHAR sName[1024];
var sName [1024]C.PRL_CHAR
// PRL_UINT32 nBufSize = sizeof(sName);
var nBufSize C.PRL_UINT32 = C.PRL_UINT32(unsafe.Sizeof(sName))
ret = C.PrlFoundVmInfo_GetName(hFoundVmInfo, (*C.PRL_CHAR)(unsafe.Pointer(&sName)), &nBufSize)
// printf("VM name: %s\n", sName);
var gName string = C.GoString((*C.char)(unsafe.Pointer(&sName)))
fmt.Printf("VM %d name: \"%s\"\n", nBufSize, gName)
What is the proper way to declare name (and nBufSize) and how do i convert name to a Go string? The above code dosen't work as I expect. It prints:
VM 1024 name: ""
...
PrlFoundVmInfo_GetName - Parameters
PRL_RESULT PrlFoundVmInfo_GetName(
PRL_HANDLE handle,
PRL_STR sName,
PRL_UINT32_PTR pnNameBufLength
);
The full documentation is available at C API Documentation - PrlFoundVmInfo_GetName
This was the solution, create a byte array and make sName point to it. When it has been used use C.GoStringN
to convert the content to a Go string.
var buf = make([]byte, 1024)
var sName C.PRL_STR = (C.PRL_STR)(unsafe.Pointer(&buf))
var nBufSize C.PRL_UINT32 = 1024
ret = C.PrlFoundVmInfo_GetName(*hFoundVmInfo, sName, &nBufSize)
gName := C.GoStringN((*_Ctype_char)(unsafe.Pointer(sName)), C.int(nBufSize))
fmt.Printf("VM %d name: \"%s\"\n", nBufSize, gName)