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;
}
"C"
ABI. I'm kind of surprised you don't get an error just from putting#[no_mangle]
on a method. – trentclextern void print_hellow(MyStruct);
andextern "C" fn print_hellow(&self)
are at odds, anyway -- they don't accept the same type.) – trentclfn print_hellow(*MyStruct)
and then you can "map that" to the member function ofMyStruct
. – hellow