- Overview
- ABI
- Use Rust from C/C++
- Use C/C++ code from Rust
- Types in FFI
- Ownership and Borrowing
- FFI: a way to talk to components compiled to machine code
- Based on platform-dependent C-Application Binary Interface (ABI)
- specific to a computing architecture -> low level, hardware dependent
- defines calling conventions for functions
- describes how arguments are passed (stack/registers)
- how results are passed back
- and how data is accessed
#[no_mangle]
pub extern "C" fn rust_function() {}
The Rust compiler mangles symbol names differently than native code linkers expect. This will tell the compiler not to be mangle names.
By default, any function you write in Rust will use the Rust ABI (which is also not stabilized). Instead, when building outwards facing FFI APIs we need to tell the compiler to use the system ABI.
Every function in your Rust-FFI API needs a corresponding C-declaration. Our function would then become
extern void rust_function();
see calling rust
example
see calling_c
example
see lib_wrapper
example
- primitive/numeric types
- pointers
Expose rust types to C:
- structs need to be re-structured:
pub struct Struct {
v: Vec<u8>,
id: u8,
}
can be used in C/C++ in this form:
#[repr(C)]
pub struct NativeStruct {
vec: *const u8,
vec_len: usize,
vec_cap: usize,
id: u8,
}
Managing memory is more complicated than in pure rust
let x = NativeStruct { ... }
// this box has to be freed by hand
let ptr = Box::into_raw(Box::new(x));
=> Free memory
// will be deallocated when out of scope
let _ = Box::from_raw(ptr);
// convert rust reference to pointer
let pointer: *const NativeStruct = &x;
see vector
example