Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust FFI. Casting to void pointer

Tags:

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 ?

like image 380
tez Avatar asked Jul 08 '15 19:07

tez


1 Answers

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

like image 60
oli_obk Avatar answered Sep 20 '22 03:09

oli_obk