如何将Go结构转换为C结构?

时间:2016-09-30 15:10:06

标签: go hash struct cgo

我想使用cgo。在C端,我有包含32个字节的结构。

struct hash {
    uint8_t bytes[32];
};

在Go尺寸上,我的类型非常相似。

type Hash [32]bytes

我想调用具有void f(struct hash)类型实例的C函数Hash。如果可能的话,我也想避免复制该值。

简单作业Chash C.struct_hash := hash不起作用:

  

不能在赋值

中使用散列(类型哈希)作为类型C.struct_hash

2 个答案:

答案 0 :(得分:2)

您可以使用unsafe包来投射数据。 Go编译器无法再在此处检查类型,因此您需要确保C.struct_hashHash之间所有内容的大小和类型相同。

Chash := *(*C.struct_hash)(unsafe.Pointer(&hash))

答案 1 :(得分:0)

考虑c中的对齐 你不能简单地做演员。 最好的方法应该是从c中分配值1到1或转到c。 但是这个过程很痛苦,因为struct很大而struct包含struct