如何使用 FFI 从 C 调用 Rust 结构的方法?
How to call a Rust struct's method from C using FFI?
我正在尝试使用 FFI 从 C 程序调用 public 函数(位于 Rust 结构的 impl 块内)。调用常规 pub fn
s 并不是太麻烦,但我试图从 struct
的 impl
块中调用 pub fn
,但没有找到正确的语法到expose/call吧。这当然是可能的,对吧?
lib.rs
#[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);
}
}
main.c
typedef struct MyStruct
{
int var;
} MyStruct;
extern MyStruct new (void);
extern void print_hellow(MyStruct);
int main()
{
MyStruct instance1;
MyStruct instance2 = new ();
printf("Instance1 var:%d\n", instance1.var);
/// successfully prints the uninitialized 'var'
printf("Instance2 var:%d\n", instance2.var);
/// successfully prints the initialized 'var'
print_hellow(instance1);
/// fails to link during compilation
return 0;
}
不,这是不可能的。您将需要为您希望访问的每个方法编写 shim 函数:
#[no_mangle]
pub unsafe extern "C" fn my_struct_print_hellow(me: *const MyStruct) {
let me = &*me;
me.print_hellow();
}
另请参阅:
- Using Rust objects from other languages(免责声明:我是主要维护者)
我正在尝试使用 FFI 从 C 程序调用 public 函数(位于 Rust 结构的 impl 块内)。调用常规 pub fn
s 并不是太麻烦,但我试图从 struct
的 impl
块中调用 pub fn
,但没有找到正确的语法到expose/call吧。这当然是可能的,对吧?
lib.rs
#[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);
}
}
main.c
typedef struct MyStruct
{
int var;
} MyStruct;
extern MyStruct new (void);
extern void print_hellow(MyStruct);
int main()
{
MyStruct instance1;
MyStruct instance2 = new ();
printf("Instance1 var:%d\n", instance1.var);
/// successfully prints the uninitialized 'var'
printf("Instance2 var:%d\n", instance2.var);
/// successfully prints the initialized 'var'
print_hellow(instance1);
/// fails to link during compilation
return 0;
}
不,这是不可能的。您将需要为您希望访问的每个方法编写 shim 函数:
#[no_mangle]
pub unsafe extern "C" fn my_struct_print_hellow(me: *const MyStruct) {
let me = &*me;
me.print_hellow();
}
另请参阅:
- Using Rust objects from other languages(免责声明:我是主要维护者)