Re:Rust FFI: Sending strings to the outside world
by GlitchMr on Sunday May 14, 2017 @12:30PM
(#14336246)
And there is a memory leak in all of that.
[ Parent
| on HN ]
Re:Rust FFI: Sending strings to the outside world
by wging on Sunday May 14, 2017 @12:32PM
(#14336257)
I was going to ask, how does Node then know to free the string when all JS pointers to it are gone?
... guess it doesn't?
Re:Rust FFI: Sending strings to the outside world
by webkike on Sunday May 14, 2017 @12:41PM
(#14336292)
When the program exits memory will be reclaimed by the kernel.
Memory leaks aren't horrible if they don't appear in loops or recursive functions (that is to say the leaked allocations do not grow with the uptime of the program). In this case it's pretty much identical to allocating memory that has the lifetime of the program.
Pretty obvious stuff but it's important to keep in mind.
Re:Rust FFI: Sending strings to the outside world
by wging on Sunday May 14, 2017 @12:44PM
(#14336310)
True, but I'd imagine the primary use case for NodeJS wrapping a Rust binary is a long-lived server process, where I'd expect this to actually matter. (Even on Lambda it might matter, given container reuse.)
Re:Rust FFI: Sending strings to the outside world
by webkike on Sunday May 14, 2017 @02:53PM
(#14336979)
Absolutely.
Re:Rust FFI: Sending strings to the outside world
by thayne on Thursday May 18, 2017 @12:21AM
(#14364788)
It might be good to mention how to free the memory. By passing the pointer back to a rust function like
#[no_mangle]
pub extern fn free_string(p: *mut c_char) {
unsafe {
let _ = CString::from_raw(p);
// optionally you could explicitly call drop, but
// that is unnecessary, since it is automatically dropped
// at end of scope
}
}
Also the `into_raw` method on CString gives you a pointer while simultaneously taking ownership of the CString, so mem::forget isn't necessary if you use `into_raw` rather than `as_ptr`.