This is a small demo of how to create a library in Rust and call it from Python (both CPython and PyPy) using the CFFI instead of ctypes
.
Based on http://harkablog.com/calling-rust-from-c-and-python.html (dead) which used ctypes
CFFI is nice because:
- Reads C declarations (parses headers)
- Works in both CPython and PyPy (included with PyPy)
- Lower call overhead than
ctypes
from either of:
brew install rust
- Multirust
I recommend installing Rust via multirust
so that you can compile projects that use unstable features (core) as well as testing for Rust 1.0,1.1, etc backwards compatibility.
The per-directory override mechanism is especially nice.
rustc treble.rs
This will create a libtreble.dylib
python test.py
<cffi.api.FFILibrary_./libtreble.dylib object at 0x1089d5490>
math from rust! 30
@devdave
I haven't touched this in years, but there is a repo over here https://github.com/seanjensengrey/rust-jna-example that expands on this for Java.
This repo shows how to expose a Levenshtein library using three methods
This example handles strings, which depending on the ratio of work to marshaling can solve many problems. After all, nearly every service call already has heavy string based overheads.