Writing such library will I have to sacrifice std? How, for example, will do I write python bindings to rust library, if possible?
Rust natively supports linking against C libraries and calling their functions directly. Of course, any function imported thus requires the unsafe keyword to actually call (because Rust can't guarantee its invariants or correctness) but that's an inconvenience we can punt until later.
Rust provides a Foreign Function Interface (FFI) to C libraries. Foreign functions must be declared inside an extern block annotated with a #[link] attribute containing the name of the foreign library.
First, indicate to Rust that you want to create a function visible to C:
#[no_mangle] pub extern "C" fn some_func() { ... }
This tells Rust to avoid mangling the output symbol and to use the C ABI.
Next, you will need to use C-compatible types when crossing the boundary. Here is some advice that has worked for me:
Box<T>
, and take it as a &T
or Box<T>
. Essentially, this means that you are giving up ownership of the structure in Rust, and giving ownership to the C code. The C code must ensure that if it passes the pointer back into a function that takes a Box, it no longer uses it.&str
and &[T]
are represented as raw::Slice while a Vec<T>
is represented as a raw::Vec.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With