Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy a Go string to a C char * via CGO in golang?

Tags:

go

cgo

I want to copy a Go string into a char * via CGO.

Am I allowed to do this something like this?

func copy_string(cstr *C.char) {

    str := "foo"
    C.GoString(cstr) = str

}
like image 513
steve landiss Avatar asked Aug 18 '16 16:08

steve landiss


2 Answers

using cstr = C.CString(str) did not work for me, so I opted for something I saw directy on CGO library: C.strcpy((*C.char)(cstr), (*C.char)(C.CString(str)))

like image 131
Luca Ruggieri Avatar answered Oct 21 '22 19:10

Luca Ruggieri


According to the cgo documentation you need to use the C.CString function to convert a Go string to a C string:

cstr = C.CString(str)

Be aware that C.CString function allocates the memory for you, but won't release it, so it is your responsability to freed the memory with a call like:

C.free(unsafe.Pointer(cstr))
like image 19
jnmoal Avatar answered Oct 21 '22 20:10

jnmoal