Skip to content

Instantly share code, notes, and snippets.

@michaelrinderle
Last active May 3, 2016 23:20
Show Gist options
  • Save michaelrinderle/c21780a896b18765feefce954458f615 to your computer and use it in GitHub Desktop.
Save michaelrinderle/c21780a896b18765feefce954458f615 to your computer and use it in GitHub Desktop.
Extending Python with Rust calls

What is Rust?

'A systems programming language that runs blazingly fast, prevents segfaults, and guarantees thread safety.' So think of it as C/C++ with out all the scariness, and we can extend Python for all our critical computation.

Install Rust

yaourt -S rust

Build new Rust library with cargo

cargo new pycall

Your Rust project has been created in the pycall directory

Once you have modified your Rust file in /src :

rustc src/lib.rs

Now that you have compiled your shared library you can hook to it in your Python Script

Run your Python Script

pypy pycall.py
<cffi.api.FFILibrary_src/liblib.so object at 0x0000000001130020>
20000
#![crate_type = "dylib"]
#[no_mangle]
pub extern fn rustex(x: i32) -> i32{
x * 2
}
#[test]
fn it_works() {
assert!(rustex(2) == 4)
}
try:
from cffi import FFI
except ImportError:
print "pip install cffi, included with PyPy"
ffi = FFI()
lib = ffi.dlopen("src/liblib.so")
print lib
ffi.cdef('int rustex(int);')
print lib.rustex(10000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment