我有一个byte.Buffer,使用binary.Write()函数将数据打包到其中。然后我需要将这个字节数组发送到一个C函数。在使用Go 1.6时,我一直没能成功弄清楚这个问题。
buf := new(bytes.Buffer) //create my buffer
....
binary.Write(buf, binary.LittleEndian, data) //write my data to buffer here
addr := (*C.uchar)(unsafe.Pointer(&buf.Bytes()[0])) //convert buffers byte array to a C array
rc := C.the_function(addr, C.int(buf.Len())) //Fails here
它在调用C函数的那一行出现了错误,错误信息为:
panic: runtime error: cgo argument has Go pointer to Go pointer
C函数:
int the_function(const void *data, int nbytes);
我能使下面的代码工作,但是将字节数组转换为字符串感觉不太对。有没有更好的方法来做这件事?这种方法是否会对数据造成副作用?
addr := unsafe.Pointer(C.CString(string(buf.Bytes()[0]))
这需要在Go 1.6下工作,该版本引入了更严格的cgo指针规则。
谢谢。
C.CString
会添加空字节,但我们通过传递确切的字符串长度来跳过它。 - JimB