I want to call C++ from Rust. C++ then allocates and fills a buffer, then Rust uses it and deallocates. However, I'd like to deliver back the function pointer to deallocate the data. This is what I tried:
In Rust:
extern "C" {
pub fn openvpn_receive(
instance: *mut OpenVpnInstance,
size: *mut size_t,
deallocate: extern "C" fn(*mut u8),
) -> *mut u8;
}
fn main() {
let size: *mut size_t;
let deallocate = extern "C" fn(*mut u8);
let data: *mut u8 = openvpn_receive(self.instance, size, deallocate);
//use data
deallocate(data);
}
In C++:
uint8_t* openvpn_receive(size_t *size, void (*deallocate_function)(uint8_t *))
{
deallocate_function = &cpp_deallocate_u8;
uint8*t data = receive_data(size);
}
But the Rust code is not valid. How can I make such thing happen?
selfin the middle of themain()function). It looks like your C++ function signature isn't right – it accepts a function pointer as an input, whereas you want to return a function pointer. You either need to make the deallocate function the return value, or accept a pointer to a function pointer, so you can write the function pointer to that memory location.deallocateshould use a colon to separate name and type. The variable should be mutable, since you want to pass a mutable pointer to it to your C++ code. And the type should beunsafe extern "C" fn(*mut u8).