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

ust*_*ion 5 c ffi rust

我需要extern "C"Rust中的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);
Run Code Online (Sandbox Code Playgroud)

如何为它编写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]))
}
Run Code Online (Sandbox Code Playgroud)

Pav*_*hov 7

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

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

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