Rust FFI. Casting to void pointer

tez picture tez · Jul 8, 2015 · Viewed 10.9k times · Source

I've a function which has prototype as below

//opaque struct
struct mosquitto;

struct mosquitto *mosquitto_new(const char *id, bool clean_session, void *obj);

In my c code, I'm calling it as below.

struct mosquitto *m = mosquitto_new(buf, true, NULL);

Now I want to call the above API in my rust code. rust-bindgen generated the following bindings

pub enum Struct_mosquitto { }
pub fn mosquitto_new(id: *const ::libc::c_char, clean_session: u8, obj: *mut ::libc::c_void) -> *mut Struct_mosquitto;

When I'm trying to call the above API, I'm getting a mismatch at 3rd argument.

let s = CString::new("ravi").unwrap();
let mqtt = mosquitto::mosquitto_new(s.as_ptr(), 1, ptr::null());

How do I pass NULL to *mut c_void?

BONUS QUESTION: How to pass a rust struct to *mut c_void ?

Answer

oli_obk picture oli_obk · Jul 8, 2015

The ptr::null() function returns a *const T, what you want is the ptr::null_mut() function, since the argument to your function is of type *mut ::libc::c_void.

For passing an actual value, have a look at the answer to Working with c_void in an FFI