ustulation ustulation - 1 year ago 140
C Question

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download