I'm learning about interfacing Rust and C++ (using the C interface). This is an example from Mozilla's guide for Rust on Android:
use std::os::raw::{c_char};
use std::ffi::{CString, CStr};
#[no_mangle]
pub extern fn rust_greeting(to: *const c_char) -> *mut c_char {
let c_str = unsafe { CStr::from_ptr(to) };
let recipient = match c_str.to_str() {
Err(_) => "there",
Ok(string) => string,
};
CString::new("Hello ".to_owned() + recipient).unwrap().into_raw()
}
as you can see, a C char pointer is expected, and it returns a C char pointer also.
I want to use a Rust code as a library on my project. This Rust code will deliver packets to me when they're ready. Therefore, I need a way to pass a callback to Rust so it can call it back when it has data. Kinda like this C++ snippet:
So, the rust 'class', MyRustType, will begin to work and deliver packets through onData. Is it possible to pass a C function as a pointer to Rust?
If not, I can pass the pointer as an uint64_t number, and make Rust pass this number + payload back to a C function, which in turn casts this uint64_t pointer into the function and calls it with the payload. But I think that since Rust is so C-friendly, there's a better way of doing this.
It's not clear to me whether you're asking what the Rust syntax is for function pointers, or something else. I think you want to do something like this:
looks like it's almost what I need. However, callback's type is function, not function pointer. Or does 'unsafe' make Rust interpret it as a C function pointer somehow?
That should work! fn() is a function pointer, and unsafe extern "C" fn(...) is a function pointer with the C ABI which is unsafe to call. See the fn docs.
That's quite odd. It looks like it's trying to link to a C++-decorated version of the symbol. However, you did specify extern "C" in your declaration, so the C++ compiler should generate an unmangled symbol. Which C++ compiler and version are you using?
Did you compile the rust library? What folder is the compiled rust library in (the .so file) and what is the name of the file? It seems like you may not be linking in the rust library.