如何分配空的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)


慕田峪7331174
浏览 195回答 1
1回答

萧十郎

如果您希望在没有额外分配和从 Go 复制的情况下对其进行初始化,则需要strings.Repeat通过 C 字符串实现该函数:func emptyString(size int) *C.char {&nbsp; &nbsp; p := C.malloc(C.size_t(size + 1))&nbsp; &nbsp; pp := (*[1 << 30]byte)(p)&nbsp; &nbsp; bp := copy(pp[:], " ")&nbsp; &nbsp; for bp < size {&nbsp; &nbsp; &nbsp; &nbsp; copy(pp[bp:], pp[:bp])&nbsp; &nbsp; &nbsp; &nbsp; bp *= 2&nbsp; &nbsp; }&nbsp; &nbsp; pp[size] = 0&nbsp; &nbsp; return (*C.char)(p)}如果不需要初始化,您可以自己简单地 malloc/calloc 指针并将其传递给您的函数。b := C.malloc(50) // or 51 if the depending on what size your function is expectingdefer C.free(unsafe.Pointer(b))C.cFunctionCall((*C.char)(b), 50)除非它被多次调用并实际上造成性能问题,否则请使用您已有的并减少您必须处理的 C 代码量。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go