i'm working in ffi library , have encountered pattern quite few times don't know how handle idiomatically.
impl canvoidstar str { fn as_cvoid_ptr(&self) -> *const c_void { let string = cstring::new(self).unwrap(); unsafe { return mem::transmute(string.as_ptr()); } } }
my intent create const *void
pointer piece of memory can hand off c function. problem here string
goes out of scope , undefined behavior in unsafe
block.
is there way can keep string
allocated on heap until whatever is using return value done it? further, there idiomatic way handle or need redesign algorithms?
it looks you're using wrong method on cstring
, , cstring::into_raw()
want. better, needs no unsafe
code until want free memory again.
while cstring::as_ptr()
returns pointer string, cstring::into_raw()
passes ownership of memory raw pointer; intended use case:
trait canvoidstar { fn as_cvoid_ptr(&self) -> *const c_void; } impl canvoidstar str { fn as_cvoid_ptr(&self) -> *const c_void { let string = cstring::new(self).unwrap(); string.into_raw() *const c_void } }
as documentation says, if ever want free it, you'll need reconstruct cstring
using cstring::from_raw()
, have dropped usual.
Comments
Post a Comment