How to represent a pointer to an array in Rust for C

℡╲_俬逩灬. 提交于 2019-12-04 03:43:55

问题


I need an extern "C" FFI function in Rust and want to accept an array of fixed size. The C code passes something like:

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

How do I write my Rust function for it ?

// 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:


You just need to use Rust's syntax for fixed size arrays:

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

Or you can always use *mut std::os::raw::c_void and transmute it to the correct type.



来源:https://stackoverflow.com/questions/39208831/how-to-represent-a-pointer-to-an-array-in-rust-for-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!