如何将 Go 的 []byte 转换为 C 的 *uint8_t

How to convert Go's []byte to C's *uint8_t

我想使用 Go 在 C 结构中设置一个 uint8_t*。 Go中的数据来自和ELF,是字节片。 这是我目前得到的错误:

cannot use &buf[0] (type *byte) as type *_Ctype_uchar in assignment

使用此代码:

args.vm_snapshot_data = &buf[0]

我该怎么做?

当我使用正确的转换时:
args.vm_snapshot_data = (*C.uint8_t)(&buf[0])
我收到此错误:
panic: runtime error: cgo argument has Go pointer to Go pointer

Golang 计算类型而不是它们的兼容性。而且只有一种方法可以转换它使用 unsafe.Pointer 作为原始值的地方。

args.vm_snapshot_data = (*C.uint8_t)(unsafe.Pointer(&buf[0]))

如果你不确定在C端使用buf slice时在Go端是否存活(垃圾收集器可能会处理它),那么你必须使用复制并手动处理它。

args.vm_snapshot_data = (*C.uint8_t)(C.CBytes(buf))

...

C.free(unsafe.Pointer(args.vm_snapshot_data))