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

2

16

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

}
Accelerometer answered 18/8, 2016 at 16:41 Comment(0)
L
26

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))
Libava answered 18/8, 2016 at 19:43 Comment(1)
better with defer C.free(unsafe.Pointer(cstr)) go will call when function returnsChorale
B
4

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)))

Braithwaite answered 8/4, 2021 at 7:28 Comment(1)
What about it didn't work?Dasyure

© 2022 - 2025 — McMap. All rights reserved.