Thursday, January 25, 2018

Foreign Function Interface of Rust

I am trying to figure out how to run Rust program in our C-written system. Then I read the FFI document.

There is a simple example.

Rust code: mymod.rs
#![crate_type = "staticlib"]
#[no_mangle]
pub extern fn hello_rust() -> *const u8
{
  "Hello from Rust\0".as_ptr()
}

C code: main.c

#include <stdio.h>

extern const char* hello_rust();

int main()
{
    printf("%s\n", hello_rust());
    return 0;
}


Build and run
$ rustc  mymod.rs --emit obj
$ gcc -c main.c -Wall
$ gcc main.o mymod.o
$ ./a.out
Hello from Rust

Notice:
Remember to use "no_mangle" attribute in the Rust source code to avoid name mangling. You can use "objdump -t" to see the symbols of a object file.

Next question:
How to load C headers into Rust program.

No comments:

Post a Comment