Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent a pointer to a C array in Rust?

Tags:

c

rust

ffi

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]))
}
like image 498
ustulation Avatar asked Aug 29 '16 14:08

ustulation


1 Answers

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

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

like image 53
Pavel Strakhov Avatar answered Nov 04 '22 22:11

Pavel Strakhov