Description
Sorry about the horrible title, but I really don't know how to else "summarize" this problem.
I tried to get an answer for this several times on StackOverflow (after documentation proved useless) and now I'm coming here. Maybe it's just a matter of updating documentation to have guarantees of a behaviour that will continue to work on future versions of Rust (the main purpose of documentation in the first place) or maybe the error is me who failed to spot the useful part.
I need to expose a Rust library to C applications and I need to expose an array of size only know at runtime to a function which will own this data and later will call a Rust function to deallocate it. I have a Vec<u8>
and I need to get this (*mut u8, usize)
tuple out of it. Later I need to get receive this same tuple and deallocate its data.
One option is to use mem::forget
+ Vec::from_raw_parts
, but this is far from ideal as shrink_to_fit
isn't guaranteed to work and I'd also need to store capacity (the C library really shouldn't need to worry about that).
The perfect option would be to use Vec::into_boxed_slice
. However, it crashed when I tried to use the pointer for the first element (slice::as_mut_ptr
) to Box::from_raw
, as it should. And I cannot pass the pointer return from Box::into_raw
to the C function, as the memory layout is unspecified and I don't have any guarantee it'll be a pointer to the first element.
How do we fix this? Update documentation? Add some extra function to Box<[T]>
like Box<[T]>::from_raw_parts(ptr: *mut T, len: usize)
?