A memory-violating love story
whoami(1)
Katharina Fey ( @spacekookie
)
whoami(2)
I do Rust things!
use[ful|less]
cratesberlin.rs
Rust promises efficient FFI to C code
What does this mean?
Application Binary Interface
Let’s talk about stability
Neither does C++
C doesn’t have an ABI
The operating system does
extern
functionsunsafe
std::os::raw
& std::ffi
contain FFI types
String
becomes CString
&str
becomes CStr
void
becomes c_void
extern "C"
as before#[no_mangle]
to preserve the function nameSome special fields in Cargo.toml
Integrating the Rust code into your build toolchain
├── CMakeLists.txt
├── reverso
│ ├── Cargo.toml
│ └── src
│ └── lib.rs
├── reverso.h
└── main.c
Note the header reverso.h
Calling this from C is easy
#include "reverso.h"
void main() {
char * greeting = "привет RustConf 👩🏽💻";
printf("'%s' reversed: '%s' \n", greeting, reverse(greeting));
}
'ривет RustConf 👩🏽💻' reversed: '💻👩🏽 fnoCtsuR тевирп'
Tweet at me @spacekookie
Like, Share & Subscribe…
Don’t write headers yourself. Use cbindgen
.h
files at compile-time😏
Put your troubles in a box ✨
#[repr(C)]
struct MyThing {
/* ... */
}
#[no_mangle]
extern "C" fn make_thing() -> Box<MyThing> {
Box::new(MyThing {
/* ... */
})
}
Remember: C is now responsible for the memory.
You can’t make the native code memory safe
Emulate Result<T,E>
with a structure
Well…
Wrap C-errors in exception throwing code
C++
exception from Rust?try
- throw
– catch
try
creates a “landing pad”
throw
walks up the stack
Then calls catch
try
Landing pad determines how to continue
catch
But which one? Filter or rethrow!
Replaced with calls into libc++
extern crate exception_rs as exception;
pub extern "C" fn oh_no() {
exception::throw(RustException { text: "Oh noes!" });
}
Oh god please don’t use this! (soon™ on crates.io)
No libc++
bindings in Rust
Invoke apropriate functions via C
shim layer
extern void *__cxa_allocate_exception(size_t thrown_size);
extern void __cxa_throw(void *e, void **t, void (*dest)(void *));
Functions are linked when C++ project is compiled
Yes. But not today
Follow me on twitter @spacekookie
Or: kookie@spacekookie.de