小编cod*_*ian的帖子

Rust FFI 将 trait 对象作为上下文来调用回调

好的,我正在努力实现以下目标:

  1. C调用生锈
  2. rust 回调 c 并在用户定义的 trait 对象上注册回调
  3. c 使用上下文调用 Rust
  4. Rust 调用上下文(trait 对象)上的回调

我一直在玩它。我走了很远,但还没有到那里。

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);
}
Run Code Online (Sandbox Code Playgroud)

锈点:

extern crate libc;


pub trait Foo {
    fn callback(&self);
}

extern …
Run Code Online (Sandbox Code Playgroud)

c ffi rust

5
推荐指数
1
解决办法
2082
查看次数

标签 统计

c ×1

ffi ×1

rust ×1