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:

  1. do not use vec::from_raw_parts unless pointer came vec originally. there no guarantee arbitrary pointer compatible vec , create giant holes in program if proceed.

  2. do not free pointer don't own. doing leads double frees, blow other large holes in program.

  3. you need know capacity of vector before can reconstruct it. example struct contains len. acceptable if len , capacity equal.

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

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -