英文:
How to initialise empty C.CString in cgo
问题
你认为在CGO中用长度为x初始化C.CString的最佳方法是什么?背景:我需要一个适当大小的char*作为C函数参数,但我认为以下代码可以改进:
// 长度为6
var buffer [6]byte
name := C.CString(string(buffer[:6]))
defer C.free(unsafe.Pointer(name))
或者
// 长度为6
name := C.CString(" ")
defer C.free(unsafe.Pointer(name))
英文:
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))
答案1
得分: 1
如果您不需要转换字符串,只需分配所需的大小:
s := C.malloc(6)
defer C.free(unsafe.Pointer(s))
英文:
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论