python - How to stop memory leaks when using `as_ptr()`? -


since it's first time learning systems programming, i'm having hard time wrapping head around rules. now, got confused memory leaks. let's consider example. say, rust throwing pointer (to string) python gonna catch.

in rust, (i'm sending pointer of cstring)

use std::ffi::cstring;  pub extern fn do_something() -> *const c_char {     cstring::new(some_string).unwrap().as_ptr() } 

in python, (i'm dereferencing pointer)

def call_rust():     lib = ctypes.cdll.loadlibrary(rustlib)     lib.do_something.restype = ctypes.c_void_p     c_pointer = lib.do_something()     some_string = ctypes.c_char_p(c_pointer).value 

now, question freeing memory. thought should freed in python, ownership pops in. because, as_ptr seems take immutable reference. so, got confused whether should free memory in rust or python (or both?). if it's gonna rust, how should go freeing when control flow has landed python?

your rust function do_something constructs temporary cstring, takes pointer it, , drops cstring. *const c_char invalid instant return it. if you're on nightly, want cstring#into_ptr instead of cstring#as_ptr, former consumes cstring without deallocating memory. on stable, can mem::forget cstring. can worry supposed free it.

freeing python tricky or impossible, since rust may use different allocator. best approach expose rust function takes c_char pointer, constructs cstring pointer (rather copying data new allocation), , drops it. unfortunately middle part (creating cstring) seems impossible on stable now: cstring::from_ptr unstable.

a workaround pass (a pointer to) entire cstring python , provide accessor function char pointer it. need box cstring , transmute box raw pointer. can have function transmutes pointer box , lets drop.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -