Hello everybody,
I'm trying to follow this tutorial (String Arguments - The Rust FFI Omnibus) to wire a C++ library to Rust.
However in my case I would need to dynamically create the string object on the C++ and want to take ownership of the memory on the Rust side.
Basically something like this:
mylib.cpp
#include <iostream>
char* hello(){
string SS;
SS = "This is a string"
auto result = new char[SS.size() + 1]; //+1 to take account for \0
memcpy(result, SS.c_str(), SS.size() + 1);
return result;
}
main.rs
extern crate libc;
use libc::c_char;
use std::ffi::CStr;
use std::str;
extern {
fn hello() -> *const c_char;
}
fn main() {
let c_buf: *const c_char = unsafe { hello() };
let c_str: &CStr = unsafe { CStr::from_ptr(c_buf) };
let str_slice: &str = c_str.to_str().unwrap();
let str_buf: String = str_slice.to_owned(); // data gets copied and memory owned by Rust
//missing: free memory allocated by C++, like libc::free(c_buf)`
}
I've two problems with the code:
a) as it is currently implemented I leak memory as result
never gets deallocated. There should be a way to trigger memory dealloc?
b) is there a way to take-over the ownership of result
in Rust without the need to copy the data (like .to_owned()
does)?
Thanks a lot!
Best,
Stefan