// Go string to C string // The C string is allocated in the C heap using malloc. // It is the caller's responsibility to arrange for it to be // freed, such as by calling C.free (be sure to include stdlib.h // if C.free is needed). funcC.CString(string) *C.char {}
// 翻译成中文: // C string在C的堆上使用malloc申请。 // 调用者有责任在合适的时候对该字符串进行释放,释放方式可以是调用C.free(调用C.free需包含stdlib.h)
另外值得说明的是,以下几种类型转换,都会发生内存拷贝
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Go string to C string funcC.CString(string) *C.char {}
// Go []byte slice to C array // 这个和C.CString一样,也需要手动释放申请的内存 funcC.CBytes([]byte)unsafe.Pointer {}
// C string to Go string funcC.GoString(*C.char)string {}
// C data with explicit length to Go string funcC.GoStringN(*C.char, C.int)string {}
// C data with explicit length to Go []byte funcC.GoBytes(unsafe.Pointer, C.int) []byte {}
==31055== 17 bytes in 1 blocks are definitely lost in loss record 1 of 4 ==31055== at 0x4C29BC3: malloc (vg_replace_malloc.c:299) ==31055== by 0x737433: _cgo_d0ada72ffd0d_Cfunc__Cmalloc (_cgo_export.c:30) ==31055== by 0x45C9DF: runtime.asmcgocall (/usr/local/go/src/runtime/asm_amd64.s:635) ==31055== by 0xD1A6BF: ??? ==31055== by 0x1FFF00030F: ??? ==31055== by 0x45A057: runtime.goready.func1 (/usr/local/go/src/runtime/proc.go:312) ==31055== by 0x45B205: runtime.systemstack (/usr/local/go/src/runtime/asm_amd64.s:351) ==31055== by 0x4331BF: ??? (/usr/local/go/src/runtime/proc.go:1082) ==31055== by 0x45B098: runtime.rt0_go (/usr/local/go/src/runtime/asm_amd64.s:201)
==31701== 134,217,728 bytes in 1 blocks are possibly lost in loss record 5 of 5 ==31701== at 0x4C29BC3: malloc (vg_replace_malloc.c:299) ==31701== by 0x73754D: f1 (main.go:12) ==31701== by 0x73754D: _cgo_3679cecbf840_Cfunc_f1 (cgo-gcc-prolog:48) ==31701== by 0x45CA5F: runtime.asmcgocall (/usr/local/go/src/runtime/asm_amd64.s:635) ==31701== by 0xD1A6BF: ??? ==31701== by 0x1FFF00031F: ??? ==31701== by 0x45A0D7: runtime.goready.func1 (/usr/local/go/src/runtime/proc.go:312) ==31701== by 0x45B285: runtime.systemstack (/usr/local/go/src/runtime/asm_amd64.s:351) ==31701== by 0x43323F: ??? (/usr/local/go/src/runtime/proc.go:1082) ==31701== by 0x45B118: runtime.rt0_go (/usr/local/go/src/runtime/asm_amd64.s:201)
==31858== 134,217,728 bytes in 1 blocks are possibly lost in loss record 6 of 6 ==31858== at 0x4C29BC3: malloc (vg_replace_malloc.c:299) ==31858== by 0x45197D: f1 (main.go:13) ==31858== by 0x4E3DDD4: start_thread (in /usr/lib64/libpthread-2.17.so) ==31858== by 0x514FEAC: clone (in /usr/lib64/libc-2.17.so)
As a special case, C.malloc does not call the C library malloc directly but instead calls a Go helper function that wraps the C library malloc but guarantees never to return nil. If C's malloc indicates out of memory, the helper function crashes the program, like when Go itself runs out of memory. Because C.malloc cannot fail, it has no two-result form that returns errno.