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);

rust

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()
}

This will be passed in, but the array received by rust is like this [1,0,2,0,3,0]

推荐答案

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

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

00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001

分别变为0x1和0x0.由于小端数,首先读取最低有效位.

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

Rust相关问答推荐

如何在 struct 中填充缓冲区并同时显示它?

如何为utoipa中的可选查询参数生成OpenAPI模式?

下载压缩文件

如何删除Mac Tauri上的停靠图标?

如何定义实现同名但返回类型不同的 struct 的函数

如何在递归数据 struct 中移动所有权时变异引用?

如何防止Cargo 单据和Cargo 出口发布( crate )项目

类型生命周期绑定的目的是什么?

为什么我必须使用 PhantomData?在这种情况下它在做什么?

如何对一个特征的两个实现进行单元测试?

Rust,如何从 Rc> 复制内部值并返回它?

为什么 Rust 需要可变引用的显式生命周期而不是常规引用?

如何使用 Bincode 在 Rust 中序列化 Enum,同时保留 Enum 判别式而不是索引?

我如何取消转义,在 Rust 中多次转义的字符串?

从 Rust 中的 if/else 中的引用创建 MappedRwLockWriteGuard

在 Rust 中,将可变引用传递给函数的机制是什么?

如何异步记忆选项中的 struct 字段

如何为枚举中的单个或多个值返回迭代器

如何将 while 循环内的用户输入添加到 Rust 中的向量?

为什么这里需要类型注解?