10

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]))
}
3
  • 1
    It's a pointer, so you can just use *mut std::os::raw::c_void in the extern function signature and transmute it to the correct type. Commented Aug 29, 2016 at 14:44
  • @PavelStrakhov: That's an answer :) Commented Aug 29, 2016 at 14:48
  • @PavelStrakhov Using the correct type gives some type safety than using void*, so i would use it only as a last resort. Doesn't rust have a solution for this you mean ? Commented Aug 29, 2016 at 14:48

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.