How to return byte array from Rust function to FFI C?

Sorry, I misread which direction you want to pass the data.

C doesn't understand Rust slices, so you can't give them to C at all. For passing data to C you have to use raw C pointers, like *const u8.

But careful with raw pointers, because they are unsafe, just like in C. Use-after-free and dangling pointers to stack variables are possible. So when you get a pointer to a Rust object, you must ensure it's not a temporary on stack (i.e. use Box to allocate it on the heap), and make sure Rust won't free it while C is still using it (that's why @vitalyd's example has mem::forget()).

Box::into_raw() and Box::from_raw() is a good pair giving pointers to C and getting them back to release the memory.

Lifetimes don't pass ownership. Lifetimes don't do anything in a running program. Lifetimes only describe to the compiler what would happen to the memory anyway (they're like assert()). 'static informs the compiler that nobody will free this memory, it's leaked and there's no cleanup.

3 Likes