英文:
How to allocate empty CString?
问题
cFunctionCall填充了b,我能够将字符串的内容传递给GO字符串。然而,我认为我的内存分配(第1行)不够高效。
b := C.CString(strings.Repeat(" ", 50))
defer C.free(unsafe.Pointer(b))
C.cFunctionCall(b, 50)
rs := C.GoString(b)
log.Printf("rs: '%v'\n", rs)
英文:
The cFunctionCall populates b and I am able to get content of string into GO string. However, I think that my memory allocation (line #1) is not efficient.
b := C.CString(strings.Repeat(" ", 50))
defer C.free(unsafe.Pointer(b))
C.cFunctionCall(b, 50)
rs := C.GoString(b)
log.Printf("rs: '%v'\n", rs)
答案1
得分: 1
如果你想要在不进行额外分配和复制的情况下进行初始化,你需要实现一个基于C字符串的strings.Repeat
函数:
func emptyString(size int) *C.char {
p := C.malloc(C.size_t(size + 1))
pp := (*[1 << 30]byte)(p)
bp := copy(pp[:], " ")
for bp < size {
copy(pp[bp:], pp[:bp])
bp *= 2
}
pp[size] = 0
return (*C.char)(p)
}
如果不需要进行初始化,你可以自己使用malloc/calloc
分配指针,并将其传递给你的函数。
b := C.malloc(50) // 或者根据你的函数期望的大小选择51
defer C.free(unsafe.Pointer(b))
C.cFunctionCall((*C.char)(b), 50)
除非这个操作被频繁调用并且实际上存在性能问题,否则请使用你已经拥有的方法,并减少你需要处理的C代码量。
英文:
If you want it to be initialized without the extra allocation and copy from Go, you would need to implement the strings.Repeat
function over a C string:
func emptyString(size int) *C.char {
p := C.malloc(C.size_t(size + 1))
pp := (*[1 << 30]byte)(p)
bp := copy(pp[:], " ")
for bp < size {
copy(pp[bp:], pp[:bp])
bp *= 2
}
pp[size] = 0
return (*C.char)(p)
}
If it doesn't need to be initialized, you can simply malloc/calloc the pointer yourself and pass it to your function.
b := C.malloc(50) // or 51 if the depending on what size your function is expecting
defer C.free(unsafe.Pointer(b))
C.cFunctionCall((*C.char)(b), 50)
Unless this is being called many times and actually poses a performance problem, use what you already have and reduce the amount of C code you have to deal with.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论