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

You can't take data pointer from C and return it to Rust as Vec. Only Rust can allocate a Vec, because it's always freed using Rust's own private allocator. If you want to return a Vec, you'll have to copy the data into it first.

There's CVec for allowing Rust to use malloc-allocated data.

&[u8] is a type that means "you never ever have to worry about freeing it", so you can return it from a function only as &'static [u8] if C leaked that memory or it's from a global/static variable in C, but that's rather rare.

1 Like