0

I'm on a situation that I need to pass a slice s: &[u8] to C++ for it to be used for a while, and then it should pass back to Rust for deletion.

I plan to pass the slice as a *const u8 by calling s.as_ptr() (anyone knows a better way?). However, the C++ function does not consume the buffer immediately. It stores it on a queue.

How should I pass this to C++ and how to delete it in Rust after usage?

Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150
  • Note that you can't ever artificially extend the lifetime of a slice. This is no exception with FFI. https://stackoverflow.com/questions/28820781/extend-lifetime-of-variable – E_net4 Jun 24 '20 at 09:25
  • 1
    See also: https://stackoverflow.com/questions/28758246/how-can-i-convert-a-vect-into-a-c-friendly-mut-t – E_net4 Jun 24 '20 at 09:25
  • 3
    I believe that the only way to do so is by making your FFI stateful. Move the structure that your slice comes from (say a `Vec`) into a map owned by your FFI object, then place the call, then once you have received a callback from C++ that you can perform the cleanup, have the FFI object perform this cleanup. – Yoric Jun 24 '20 at 10:08
  • 3
    Have you considered simply copying the slice on the C++ side? Then you wouldn't have to worry about the interaction between Rust and C++ lifetimes, each side would manage things on its own. – Matthieu M. Jun 24 '20 at 14:04

0 Answers0