首页 文章

如何在Rust for C中表示指向数组的指针

提问于
浏览
5

我需要在Rust中使用 extern "C" FFI函数,并希望接受一个固定大小的数组 . C代码传递的内容如下:

// C code
extern int(*)[4] call_rust_funct(unsigned char (*)[3]);
....
unsigned char a[] = { 11, 255, 212 };
int(*p)[4] = call_rust_funct(&a);

如何为它编写Rust函数?

// Pseudo code - DOESN'T COMPILE
pub unsafe extern "C" fn call_rust_funct(_p: *mut u8[3]) -> *mut i32[4] {
    Box::into_raw(Box::new([99i32; 4]))
}

1 回答

  • 7

    您只需要将Rust的语法用于固定大小的数组:

    pub unsafe extern "C" fn call_rust_funct(_p: *mut [u8; 3]) -> *mut [i32; 4] {
       Box::into_raw(Box::new([99i32; 4]))
    }
    

    或者,您始终可以使用 *mut std::os::raw::c_void 并将其转换为正确的类型 .

相关问题