What is the right way to allocate data to pass to an FFI call?

Ideally you would use std::alloc::alloc because you can then specify the desired alignment as part of the layout:

pub unsafe fn alloc(layout: Layout) -> *mut u8

The main downside is that you need to know the alignment, even when you free the allocation.

It’s common practice to use a Vec as an easy allocation mechanism, but you need to be careful when using it as such.

  1. Make sure that your units are correct — is the “length” parameter the number of items or the number of bytes?
  2. If you dissolve the Vec into component parts, you need to
    1. track the length and the capacity. Some people use shrink_to_fit to ensure those two values are the same.
    2. Avoid crossing the streams – that memory was allocated by Rust and must be freed by Rust. Convert it back into a Vec to be dropped.
  3. Beware that an empty Vec does not have a NULL pointer!:

    fn main() {
        let v: Vec<u8> = Vec::new();
        println!("{:p}", v.as_ptr());
        // => 0x1
    }
    

For your specific case, I might suggest using the capacity of the Vec instead of tracking the second variable yourself. You’ll note that you forgot to update pcb_buffer after the first call, so I’m pretty sure that the code will always fail. It’s annoying because it needs to be a mutable reference so you can’t completely get away from it.

Additionally, instead of extending the Vec, you could just reserve space.

There’s also no guarantee that the size required during the first call will be the same as the size required during the second call. You could do some kind of loop, but then you have to worry about an infinite loop happening.

Leave a Comment