Search code examples
rustffi

Test FFI functions in Rust


I have a lib in Rust that exposes some FFI functions and I would like to know how to call these functions in a console app and if there is a way to test them via the Linux terminal?

PS: I know the lib is working because I can make the call in C#.

lib implementation:

const CUR_VERSION: &str = "0.1";

#[no_mangle]
pub extern "C" fn get_version() -> *const c_char {
    let c_string = CString::new(CUR_VERSION).expect("CString::new failed");
    c_string.into_raw()
}

In the console application I tried this without success:

extern crate core;
use std::ffi::c_char;

#[cfg_attr(unix, link(name = "my_dll.so", kind = "dylib"))]
extern "C" {
    fn get_version() -> *const c_char;
}

fn main() {
    unsafe {
        println!("Result: {:?}", get_version());
    }
}

Error Code

enter image description here


Solution

  • The name passed to link is not the file name, it's the library name. On Linux, file names are made from library names by adding a .so extension and a lib prefix. So a library foo will have a file name libfoo.so.