如何使用 FFI 从 C 调用 Rust 结构的方法?

sam*_*sam 3 c ffi rust

我正在尝试使用 FFI 从 C 程序调用公共函数(位于 Rust 结构的 impl 块内)。调用常规pub fns 并没有太多麻烦,但我试图pub fn从 astructimpl块内部调用 a ,但没有找到正确的语法来公开/调用它。这当然是可能的,对吧?

库文件

#[repr(C)]
#[derive(Debug)]
pub struct MyStruct {
    var: i32,
}

#[no_mangle]
pub extern "C" fn new() -> MyStruct {
    MyStruct { var: 99 }
}

#[no_mangle]
impl MyStruct {
    #[no_mangle]
    pub extern "C" fn print_hellow(&self) {
        println!("{}", self.var);
    }
}
Run Code Online (Sandbox Code Playgroud)

主文件

#[repr(C)]
#[derive(Debug)]
pub struct MyStruct {
    var: i32,
}

#[no_mangle]
pub extern "C" fn new() -> MyStruct {
    MyStruct { var: 99 }
}

#[no_mangle]
impl MyStruct {
    #[no_mangle]
    pub extern "C" fn print_hellow(&self) {
        println!("{}", self.var);
    }
}
Run Code Online (Sandbox Code Playgroud)

She*_*ter 5

不,这是不可能的。您需要为要访问的每个方法编写填充函数:

#[no_mangle]
pub unsafe extern "C" fn my_struct_print_hellow(me: *const MyStruct) {
    let me = &*me;
    me.print_hellow();
}
Run Code Online (Sandbox Code Playgroud)

也可以看看: