我从 Go 调用以下 C 函数:
char *my_read(int dd) {
char *buf = malloc(sizeof(char) * BUF_SUZE);
if (!buf) {
return NULL; // cannot allocate memory
}
while (read(dd, buf, BUF_SIZE) < 0) {
if (errno == EAGAIN || errno == EINTR) {
continue;
}
break;
}
return buf;
}
我的 Go 代码如下所示:
//#include "hci_cgo.h"
import "C"
func MyRead(dd int) ([]byte, error) {
data, err := C.my_read(dd)
if err != nil {
return nil, err
}
if data == nil {
return nil, errors.New("my_read: cannot allocate memory")
}
// Here we create a Go slice of the data, but the C buffer is kept forever:
return C.GoBytes(unsafe.Pointer(data), C.BUF_SIZE)
}
我应该如何修改MyRead
(或相应的 C 代码)以在从返回之前释放分配的缓冲区MyRead
?
或者,我可以在 C 中重复使用单个缓冲区,从而完全避免分配,并在返回[]byte
后创建数据的 Go 副本吗?C.my_read(…)
如果是这样,我可以放入一个互斥锁MyRead
以确保对 的顺序调用C.my_read(…)
,但是如何将 C 缓冲区复制到 Go 以便 GC 知道呢?