Rust FFI. 转换为 void 指针

21

我有一个函数,其原型如下:

//opaque struct
struct mosquitto;

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

在我的 C 代码中,我像下面这样调用它。

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

现在我想在我的 Rust 代码中调用上面的 API。 rust-bindgen 生成了以下绑定。
pub enum Struct_mosquitto { }
pub fn mosquitto_new(id: *const ::libc::c_char, clean_session: u8, obj: *mut ::libc::c_void) -> *mut Struct_mosquitto;

当我试图调用上述API时,第三个参数不匹配。
let s = CString::new("ravi").unwrap();
let mqtt = mosquitto::mosquitto_new(s.as_ptr(), 1, ptr::null());

我如何将NULL传递给*mut c_void?

BONUS QUESTION: 如何将 Rust 结构体传递给*mut c_void?

1个回答

21
ptr::null()函数返回一个*const T,而你需要的是ptr::null_mut()函数,因为你的函数参数的类型是*mut ::libc::c_void

如果要传递实际值,请参考在FFI中使用c_void的答案。


谢谢。这行代码可行。有没有一种方法可以打印由mqtt指向的结构体?当我尝试这样做时,会出现紧急情况--> println!(“mqtt = {:?}”,*mqtt); - tez
也许你的 mosquitto_new 函数返回了 NULL,或者是因为你使用了一个空枚举作为表示。空枚举无法构造,因此 Rust 在与空枚举交互的任何代码之前插入了 unreachable!() 调用。这里有一个最小化的示例:http://is.gd/BOEDgb - oli_obk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接