Search code examples
gocgo

How to initialise empty C.CString in cgo


What do you think is the best way to initialise a C.CString with length x in CGO? Background: I need a char* of a proper size for a C function parameter, but I suppose following code can be improved:

// length = 6
var buffer [6]byte
name := C.CString(string(buffer[:6]))
defer C.free(unsafe.Pointer(name))

or

// length = 6
name := C.CString("      ")
defer C.free(unsafe.Pointer(name))

Solution

  • If you don't need to convert a string, just malloc the size you need:

    s := C.malloc(6)
    defer C.free(unsafe.Pointer(s))