How to allocate empty CString?

huangapple go评论95阅读模式
英文:

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 &lt;&lt; 30]byte)(p)
	bp := copy(pp[:], &quot; &quot;)
	for bp &lt; 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.

huangapple
  • 本文由 发表于 2016年4月9日 02:41:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/36506976.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定