How to allocate and fill a C++ uint8_t* buffer on Rust side?

I need a function that receives a simple C struct and fills it with the content of a vector which comes from a queue received: Arc<Mutex<VecDeque<Vec<u8>>>>.

However I'm in doubt about how to copy the data from the vector to the C buffer. I cannot allocate on C++ because I don't know the size of the buffer I'm gonna receive. So I have to allocate on Rust. Is it possible to allocate in a way that C++ can delete? If not, that's ok, but how should I allocate in Rust anyway in order to fill CBuffer?

    pub struct CBuffer {
        data: *mut u8,
        len: usize,
    pub fn receive(&mut self, cbuffer: *mut CBuffer) -> u8 {
            let s;
                s = self.received.lock().unwrap().pop_front().unwrap();
            *cbuffer = CBuffer {
                data: ?,
                len: s.len(),

You can write a function with a size argument that allocates the buffer in C++ and call that one back.

Or if you want to avoid copying and consume the Vec anyways, then you can provide a function for deallocating the CBuffer in Rust and call that one from the C++ destructor. In this case, Vec has an additional field though, the capacity (which can be bigger than len), so you would either need to hold the capacity in the CBuffer struct as well (and use into_raw_parts and from_raw_parts on Vec, one direction in receive, the other in the helper function for the C++ destructor) or consider using Box<[u8]> in the first place (or use into_boxed_slice but that one will copy the data again if the capacity was too high).

For the Box<[u8]> you can go through leak or from_raw on Box combined with slice::from_raw_parts_mut (and an implicit coercion &mut [u8] to *mut [u8]) or as_mut_prt and len on &mut [u8].

Edit: There’s also bindings to malloc in Rust, for example here or perhaps also here(?). Never tried those myself, it is possible that this does not interoperate well with C++ on all platforms. I’d say the approach of just providing a function for deallocation is safer.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.