简体   繁体   English

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

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

I want to set a uint8_t* in a C struct using Go.我想使用 Go 在 C 结构中设置一个 uint8_t*。 The data in Go comes from and ELF and is a byte slice. Go中的数据来自和ELF,是一个字节片。 This is the error I currently get:这是我目前得到的错误:

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

using this code:使用此代码:

args.vm_snapshot_data = &buf[0]

How do I do it?我该怎么做?

When I use the proper cast:当我使用正确的演员表时:
args.vm_snapshot_data = (*C.uint8_t)(&buf[0])
I get this error:我收到此错误:
panic: runtime error: cgo argument has Go pointer to Go pointer

Golang count types rather than compatibility of them. Golang 计数类型而不是它们的兼容性。 And there's only one method to cast over the place it's using unsafe.Pointer as original value.并且只有一种方法可以转换它使用unsafe.Pointer作为原始值的地方。

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

If you're not sure if buf slice will be alive on the Go side (garbage collector might dispose it) at the time when C side using it, then you have to use copy and dispose it manually.如果你不确定 buf slice 在 C 端使用它时 Go 端是否还活着(垃圾收集器可能会处理它),那么你必须使用 copy 并手动处理它。

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

...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM