我有一个 C 结构体Foo
带有函数指针。在我的 Rust 绑定中,我希望允许用户设置此函数指针,但我希望避免用户必须处理 FFI 类型。
foo.h
struct Foo {
void* internal;
uint8_t a;
void (*cb_mutate_a)(void*);
};
struct Foo* foo_new();
void foo_free(struct Foo* foo);
void foo_call(struct Foo* foo);
foo.c
struct Foo* foo_new() {
return calloc(1, sizeof(struct Foo));
}
void foo_free(struct Foo* foo) {
free(foo);
}
void foo_call(struct Foo* foo) {
return foo->cb_mutate_a(foo->internal);
}
我当前的解决方案是创建一个 Rust 结构Bar
它有一个指向bindgen生成的C结构体的指针foo_sys::Foo
,其中我有一个特征对象(rust_cb
)这是我想在 Rust API 中公开的实际回调。我设置的是Ccb
指向一个wrapped_cb
并设置internal
指向的指针Bar
,这样我就可以打电话rust_cb
从内部wrapped_cb
.
该代码可以工作,但会抱怨访问未初始化的内存。当我用 Valgrind 运行它时,我看到invalid reads
在我访问的地方(*bar).rust_cb
inside wrapped_cb
。我不确定我做错了什么。
extern crate libc;
use std::ffi;
#[repr(C)]
#[derive(Debug, Copy)]
pub struct Foo {
pub internal: *mut libc::c_void,
pub a: u8,
pub cb_mutate_a: ::core::option::Option<unsafe extern "C" fn(arg1: *mut libc::c_void)>,
}
impl Clone for Foo {
fn clone(&self) -> Self {
*self
}
}
extern "C" {
pub fn foo_new() -> *mut Foo;
}
extern "C" {
pub fn foo_free(foo: *mut Foo);
}
extern "C" {
pub fn foo_call(foo: *mut Foo);
}
struct Bar {
ptr: *mut Foo,
rust_cb: Option<Box<dyn FnMut(&mut u8)>>,
}
impl Bar {
fn new() -> Bar {
unsafe {
let mut bar = Bar {
ptr: foo_new(),
rust_cb: Some(Box::new(rust_cb)),
};
(*bar.ptr).cb_mutate_a = Some(cb);
let bar_ptr: *mut ffi::c_void = &mut bar as *mut _ as *mut ffi::c_void;
(*bar.ptr).internal = bar_ptr;
bar
}
}
}
impl Drop for Bar {
fn drop(&mut self) {
unsafe {
foo_free(self.ptr);
}
}
}
extern "C" fn cb(ptr: *mut libc::c_void) {
let bar = ptr as *mut _ as *mut Bar;
unsafe {
match &mut (*bar).rust_cb {
None => panic!("Missing callback!"),
Some(cb) => (*cb)(&mut (*(*bar).ptr).a),
}
}
}
fn rust_cb(a: &mut u8) {
*a += 2;
}
fn main() {
unsafe {
let bar = Bar::new();
let _ = foo_call(bar.ptr);
}
}
我查看了相关问题,这些问题似乎回答了我的问题,但解决了不同的问题:
- Rust FFI 将特征对象作为上下文传递以调用回调 https://stackoverflow.com/q/33929079/155423
这使用dlsym
从 C 调用 Rust 回调。
- 如何将 Rust 闭包转换为 C 风格回调? https://stackoverflow.com/q/32270030/155423
- 如何通过原始指针将闭包作为参数传递给 C 函数? https://stackoverflow.com/q/38995701/155423
这些描述了将闭包作为 C 函数指针传递的解决方案。
我想要实现的是拥有一个 Rust 结构(Bar
) 有一个成员变量ptr
指向一个 C 结构体(Foo
),它本身有一个void *internal
指向 Rust 结构体Bar
.
这个想法是在 Rust 结构中拥有一个特征对象和包装函数Bar
C 结构体中的每个函数指针Foo
。当一个Bar
创建对象后,我们执行以下操作:
- 创建C
Foo
并保留一个指向它的指针Bar
.
- Point
Foo->callback
包装 Rust 函数。
- Point
Foo->internal
to Bar
.
由于包装函数传递了internal
指针,我们可以得到一个指向Bar
并调用相应的闭包(来自特征 obj)。
我能指出Cvoid*
到我的 Rust 结构,我还可以从 Rust 回调(或闭包)获取指向它的指针,这就是相关问题所解决的问题。问题我am面临的问题可能与生命周期有关,因为其中一个值的生命周期不够长,无法在回调中使用。