title: Is it possible to receive a pointer to C function in Rust and call it back?
body: <p>I'm learning about interfacing Rust and C++ (using the C interface). This is an example from Mozilla's guide for Rust on Android:</p>
  
  <pre><code>use std::os::raw::{c_char};
  use std::ffi::{CString, CStr};
  
  #[no_mangle]
  pub extern fn rust_greeting(to: *const c_char) -&gt; *mut c_char {
      let c_str = unsafe { CStr::from_ptr(to) };
      let recipient = match c_str.to_str() {
          Err(_) =&gt; "there",
          Ok(string) =&gt; string,
      };
  
      CString::new("Hello ".to_owned() + recipient).unwrap().into_raw()
  }
  </code></pre>
  
  <p>as you can see, a C char pointer is expected, and it returns a C char pointer also.</p>
  
  <p>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:</p>
  
  <pre><code>extern "C" onData(uint8_t* payload, size_t size) {
      //do something with payload
  }
  
  MyRustType myRustObject("initialization_string");
  myRustObject.setOnDataCallback(&amp;onData);
  myRustObject.beginWork();
  </code></pre>
  
  <p>So, the rust 'class', <code>MyRustType</code>, will begin to work and deliver packets through <code>onData</code>. Is it possible to pass a C function as a pointer to Rust?</p>
  
  <p>If not, I can pass the pointer as an <code>uint64_t</code> 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.</p>