【发布时间】:2016-02-28 23:38:31
【问题描述】:
好的,我正在努力实现以下目标:
- C 调用 rust
- rust 回调到 c 并在用户定义的 trait 对象上注册回调
- c 在上下文中调用 rust
- rust 在上下文(特征对象)上调用回调
我一直在玩它。我已经走了很远,但还没有到达那里。
C位:
#include <dlfcn.h>
#include <stdio.h>
void *global_ctx;
void c_function(void* ctx) {
printf("Called c_function\n");
global_ctx = ctx;
}
int main(void) {
void *thing = dlopen("thing/target/debug/libthing.dylib", RTLD_NOW | RTLD_GLOBAL);
if (!thing) {
printf("error: %s\n", dlerror());
return 1;
}
void (*rust_function)(void) = dlsym(thing, "rust_function");
void (*rust_cb)(void*) = dlsym(thing, "rust_cb");
printf("rust_function = %p\n", rust_function);
rust_function();
rust_cb(global_ctx);
}
锈迹:
extern crate libc;
pub trait Foo {
fn callback(&self);
}
extern {
fn c_function(context: *mut libc::c_void);
}
pub struct MyFoo;
impl Foo for MyFoo {
fn callback(&self) {
println!("callback on trait");
}
}
#[no_mangle]
pub extern fn rust_cb(context: *mut Foo) {
unsafe {
let cb:Box<Foo> = Box::from_raw(context);
cb.callback();
}
}
#[no_mangle]
pub extern fn rust_function() {
println!("Called rust_function");
let tmp = Box::new(MyFoo);
unsafe {
c_function(Box::into_raw(tmp) as *const Foo as *mut libc::c_void);
}
}
问题:
- 当我尝试对“rust_cb”中的特征对象调用“回调”时,我的程序出现段错误
一个解决方案: - 将“rust_cb”的函数签名更改为
pub extern fn rust_cb(context: *mut MyFoo)
但这不是我想要的,因为我正在尝试创建一个只知道侦听器特征的安全包装器
任何帮助表示赞赏
PS:我的假设是它有段错误,因为编译器不知道回调在特征 Foo 上的偏移量,它需要实际的对象来确定它在哪里。但后来我不知道如何解决这个问题
【问题讨论】: