21

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 ?

tez
  • 4,990
  • 12
  • 47
  • 67

1 Answers1

21

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

Community
  • 1
  • 1
oli_obk
  • 28,729
  • 6
  • 82
  • 98
  • Thanks. That worked. Is there a way that I could print the struct pointed by `mqtt` ? I'm getting a panic when I try this --> println!("mqtt = {:?}", *mqtt); – tez Jul 09 '15 at 04:21
  • maybe your `mosquitto_new` function returns a NULL, or it's because you are using an empty enum as representation. An empty enum cannot be constructed, therefor Rust inserts `unreachable!()` calls before any code that does interact with empty enums. Here's a minimal example: http://is.gd/BOEDgb – oli_obk Jul 09 '15 at 06:29