Calling from C++ code
I've never done any Rust before so I'm sure that this question probably comes down to my lack of experience, but it could be helpful to someone else who stumbles across this. I'm interested in calling RustFFT in my C++ code because I am getting much better performance on an ARM processor than FFTW.
I've created a lib.rs that externs the functions into c++ and having some lifetime issues.
#[no_mangle]
pub extern "C" fn create_fft_fc64() -> *mut FftPlanner<f64> {
return Box::into_raw(Box::new(FftPlanner::new()));
}
#[no_mangle]
pub extern "C" fn free_fft_fc64(plan: *mut FftPlanner<f64>) {
unsafe{drop(Box::from_raw(plan))};
}
...
I build the package and can successfully link to and run it from my c++ code. Everything works great as long as I only have 1 planner object at a time. If I create two objects they are getting the same pointer. When I call free on both of them, the program crashes.
auto p1 = create_fft_fc64();
auto p2 = create_fft_fc64();
free_fft_fc64(p1);
free_fft_fc64(p2); // Fails with double free error
I see that the FftPlanner creates an Arc. So I tried creating the raw pointer from the Arc instead of a box:
#[no_mangle]
pub extern "C" fn create_fft_fc64() -> *mut FftPlanner<f64> {
return Arc::into_raw(FftPlanner::<f64>::new().into()) as *mut FftPlanner<f64>;
//return Box::into_raw(Box::new(FftPlanner::new()));
}
#[no_mangle]
pub extern "C" fn free_fft_fc64(plan: *mut FftPlanner<f64>) {
unsafe{drop(Arc::from_raw(plan))};
}
This eliminates the double free error, but I get a segfault when I try to execute the FFT (after I free the first one). I know this probably comes down to just a lack of understanding of the rust ownership model, but any help would be greatly appreciated.