CGO如何将切片传给铁锈

  • 本文关键字:切片 CGO go rust ffi cgo
  • 更新时间 :
  • 英文 :


golang

input := []uint{1,2,3,4,5,6}
o := C.fixU32_encode((*C.uint)(unsafe.Pointer(&input[0])), C.size_t(len(input)))
return C.GoString(o)

c

char* fixU32_encode(unsigned int* ptr,size_t length);

锈蚀

pub extern "C" fn fixU32_encode(ptr: *const u32, length: libc::size_t) -> *const libc::c_char {
assert!(!ptr.is_null());
let slice = unsafe {
std::slice::from_raw_parts(ptr, length as usize)
};
println!("{:?}", slice);// there will print [1,0,2,0,3,0]
println!("{:?}", length);
let mut arr = [0u32; 6];
for (&x, p) in slice.iter().zip(arr.iter_mut()) {
*p = x;
}
CString::new(hex::encode(arr.encode())).unwrap().into_raw()
}

这会被传递进来,但铁锈收到的数组是这样的[1,0,2,0,3,0]

在Go中,uint是64位(请参阅https://golangbyexample.com/go-size-range-int-uint/)。因此,您将在input中存储64位整数。

C代码和Rust代码现在处理的input是32位无符号整数(采用小端序格式)。因此,64位中0x1的第一个输入:

00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001

分别变为0x1和0x0。由于字节序小,所以首先读取最低有效位。

您希望在Go中指定使用uint32使用32位,或者确保您的C代码与Go中的机器相关整数类型匹配。

最新更新