简体   繁体   中英

How to call a Rust struct's method from C using FFI?

I am trying to call a public function (located inside a Rust struct's impl block) from a C program using the FFI. Calling regular pub fn s has not been too much trouble, but I am trying to call a pub fn from inside a struct 's impl block, and not finding the right syntax to expose/call it. Surely this is possible, right?

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;
}

No, this is not possible. You will need to write shim functions for every method you wish to access:

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

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM