How to initialise empty C.CString in cgo

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

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))

huangapple
  • 本文由 发表于 2017年1月31日 17:14:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/41953619.html
匿名

发表评论

匿名网友

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

确定