Skip to content

Instantly share code, notes, and snippets.

@apendleton
Forked from aravindavk/gist:2b4298eeb2d8f949224b
Last active August 29, 2015 14:06
Show Gist options
  • Save apendleton/665447c169789b3d9f62 to your computer and use it in GitHub Desktop.
Save apendleton/665447c169789b3d9f62 to your computer and use it in GitHub Desktop.
use std::num::pow;
pub struct Point { x: int, y: int }
struct Line { p1: Point, p2: Point }
impl Line {
pub fn length(&self) -> f64 {
let xdiff = self.p1.x - self.p2.x;
let ydiff = self.p1.y - self.p2.y;
((pow(xdiff, 2) + pow(ydiff, 2)) as f64).sqrt()
}
}
#[no_mangle]
pub extern "C" fn make_point(x: int, y: int) -> Box<Point> {
box Point { x: x, y: y }
}
#[no_mangle]
pub extern "C" fn get_distance(p1: &Point, p2: &Point) -> f64 {
Line { p1: *p1, p2: *p2 }.length()
}
#!/usr/bin/env python
"""
Consumer example to use the shared object created in Rust.
Ref: http://blog.skylight.io/bending-the-curve-writing-safe-fast-native-gems-with-rust/
"""
from cffi import FFI
import os, sys
RUST_SO_PATH = os.path.join(os.path.dirname(__file__), "libpoints.%s" % ('dylib' if sys.platform == 'darwin' else 'so'))
ffi = FFI()
ffi.cdef("""
typedef struct {
int x, y;
} Point;
""")
ffi.cdef("double get_distance(Point* p1, Point* p2);")
ffi.cdef("Point* make_point(int x, int y);")
api = ffi.dlopen(RUST_SO_PATH)
make_point, get_distance = api.make_point, api.get_distance
p1 = make_point(10, 10)
p2 = make_point(20, 20)
print get_distance(p1, p2)
#!/usr/bin/env python
"""
Consumer example to use the shared object created in Rust.
Ref: http://blog.skylight.io/bending-the-curve-writing-safe-fast-native-gems-with-rust/
"""
from ctypes import CDLL, Structure, c_int, c_void_p
from ctypes import c_double, CFUNCTYPE
import os, sys
RUST_SO_PATH = os.path.join(os.path.dirname(__file__), "libpoints.%s" % ('dylib' if sys.platform == 'darwin' else 'so'))
class Point (Structure):
_fields_ = [
("x", c_int),
("y", c_int)
]
api = CDLL(RUST_SO_PATH)
make_point = CFUNCTYPE(c_void_p, c_int, c_int)(('make_point', api))
get_distance = CFUNCTYPE(c_double, c_void_p, c_void_p)(('get_distance', api))
p1 = make_point(10, 10)
p2 = make_point(20, 20)
print get_distance(p1, p2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment