rust - How to convert a *const pointer into a Vec to correctly drop it? -
after asking how should go freeing memory across ffi boundary, on rust reddit suggested rather wrapping structs in box, use vec::from_raw_parts construct vector following struct, , safely dropped:
#[repr(c)] pub struct array { data: *const c_void, len: libc::size_t, } however, from_raw_parts seems require *mut _ data, i'm not sure how proceed…
the short answer self.data *mut u8. but, let's talk more details...
first, words of warning:
do not use
vec::from_raw_partsunless pointer camevecoriginally. there no guarantee arbitrary pointer compatiblevec, create giant holes in program if proceed.do not free pointer don't own. doing leads double frees, blow other large holes in program.
you need know capacity of vector before can reconstruct it. example struct contains
len. acceptable iflen,capacityequal.
now, let's see if can follow own rules...
extern crate libc; use std::mem; #[repr(c)] pub struct array { data: *const libc::c_void, len: libc::size_t, } // note both of these methods should implementations // of `from` trait allow them participate in more places. impl array { fn from_vec(mut v: vec<u8>) -> array { v.shrink_to_fit(); // ensure capacity == size let = array { data: v.as_ptr() *const libc::c_void, len: v.len(), }; mem::forget(v); } fn into_vec(self) -> vec<u8> { unsafe { vec::from_raw_parts(self.data *mut u8, self.len, self.len) } } } fn main() { let v = vec![1, 2, 3]; let = array::from_vec(v); let v = a.into_vec(); println!("{:?}", v); } note don't have explicit dropping of vec because normal drop implementation of vec comes play. have make sure construct vec properly.
Comments
Post a Comment