Can a stack allocated Rust buffer accessed through C++

In order to avoid head allocations, and since I know the maximum MTU of an ethernet packet, I created a small buffer: [u8, MAX_BYTES_TRANSPORT] in Rust, that C++ should fill for me:

pub fn receive(&mut self, f: &dyn Fn(&[u8])) -> std::result::Result<(), &str> {
    let mut buffer: [u8; MAX_BYTES_TRANSPORT] = [0; MAX_BYTES_TRANSPORT];
    //number of bytes written in buffer in the C++ side
    let written_size: *mut size_t = std::ptr::null_mut::<size_t>();
    let r = unsafe{openvpn_client_receive_just(buffer.as_mut_ptr(), buffer.len(), written_size, self.openvpn_client)};

This is the function:

uint8_t openvpn_client_receive_just(uint8_t *buffer, size_t buffer_size, size_t *written_size, OpenVPNSocket *client)

So, the function openvpn_client_receive_just, which is a C++ function with C interface, should write to this buffer. Is this safe? I couldn't find information about a stack allocated Rust buffer being used in C++

Yes, writing to a Rust stack allocated buffer from C++ should be fine. Unlike managed languages, there is no difference between the heap's memory and the stack's memory (nor is there between rust's memory and C++'s memory).

The only memory-related concern from the point of view of Rust <-> C or C++ FFI (apart from lifetimes, obviously) is that dynamically allocated memory must be freed by the same allocator that allocated it. So you must not e.g. free() or delete the buffer of a Box or a Vec, and conversely, you must not write drop(Box::from_raw(ptr)) on a malloc()'d or new'd buffer.

So reading from and writing to memory is always OK in this respect; the allocator does not and should not matter.

Of course, many badly-designed C and C++ libraries rely on globals and store pointers in hidden state, so you must always ensure that you don't accidentally use memory after it's freed, and conversely, that you don't accidentally free it (either explicitly or automatically) while someone else is trying to use it. But this is true for all memory; whether it's stack-allocated or heap-allocated does not matter.

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.