Skip to content

Instantly share code, notes, and snippets.

@rtorr
Last active August 29, 2015 14:07
Show Gist options
  • Save rtorr/3dd2b1b07abd6afcda0f to your computer and use it in GitHub Desktop.
Save rtorr/3dd2b1b07abd6afcda0f to your computer and use it in GitHub Desktop.
rustc points.rs --crate-type=dylib
npm install
node test.js
{
"name": "rusty",
"version": "0.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"ffi": "^1.2.7",
"node-ffi": "^0.5.7"
}
}
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 get_distance(p1: &Point, p2: &Point) -> f64 {
Line { p1: *p1, p2: *p2 }.length()
}
#[no_mangle]
pub extern "C" fn make_point(x: int, y: int) -> Box<Point> {
box Point { x: x, y: y }
}
var ffi = require('ffi');
var RustPoint = ffi.Library('./libpoints', {
'make_point': [ 'pointer', [ 'int', 'int'] ],
'get_distance': [ 'double', [ 'pointer', 'pointer'] ]
});
var p1 = RustPoint.make_point(10, 10);
var p2 = RustPoint.make_point(20, 20);
console.log(RustPoint.get_distance(p1, p2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment