Skip to content

Instantly share code, notes, and snippets.

@hamin
Last active August 29, 2015 14:26
Show Gist options
  • Save hamin/9802e7289cfd5fb5ac22 to your computer and use it in GitHub Desktop.
Save hamin/9802e7289cfd5fb5ac22 to your computer and use it in GitHub Desktop.
An updated Rust 1.x version of Yehuda's Native Rust Extension post here http://blog.skylight.io/bending-the-curve-writing-safe-fast-native-gems-with-rust/
require "./points"
p1 = RustPoint::make_point(10, 10) # => #<Fiddle::Pointer:0x007f8231e56510 ptr=0x0000010b824000 size=0 free=0x00000000000000>
p2 = RustPoint::make_point(20, 20) # => #<Fiddle::Pointer:0x007f8231f20970 ptr=0x0000010b824010 size=0 free=0x00000000000000>
RustPoint::get_distance(p1, p2) # => 14.142135623730951
require "fiddle"
require "fiddle/import"
module RustPoint
extend Fiddle::Importer
dlload "./libpoints.dylib"
extern "Point* make_point(double, double)"
extern "double get_distance(Point*, Point*)"
end
// Compile this in the command like so:
// rustc points.rs --crate-type=dylib
#[derive(Copy, Clone)]
pub struct Point {
x: f64,
y: f64
}
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;
return (xdiff.powi(2) + ydiff.powi(2)).sqrt();
}
}
#[no_mangle]
pub extern "C" fn make_point(x: f64, y: f64) -> Box<Point>{
Box::new( Point{x:x, y:y} )
}
#[no_mangle]
pub extern "C" fn get_distance(p1: &Point, p2: &Point) -> f64{
Line { p1: *p1, p2: *p2}.length()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment