Skip to content

Instantly share code, notes, and snippets.

@AndrewJakubowicz
Created March 19, 2018 17:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AndrewJakubowicz/be2d3f4ba9f0bc828ff3eff76315c0e3 to your computer and use it in GitHub Desktop.
Save AndrewJakubowicz/be2d3f4ba9f0bc828ff3eff76315c0e3 to your computer and use it in GitHub Desktop.
Example of using neon after `neon new ... ` step
// JS calling Rust
var addon = require('../native');
console.log(addon.hello());
// -> "hello node"
console.log(addon.adder(1,2));
// -> 3
console.log(addon.objAdder({a: 2, b: 5}));
// -> {result: 7}
#[macro_use]
extern crate neon;
use neon::vm::{Call, JsResult};
use neon::js::{JsNumber, JsObject, JsString};
fn hello(call: Call) -> JsResult<JsString> {
let scope = call.scope;
Ok(JsString::new(scope, "hello node").unwrap())
}
fn adder(call: Call) -> JsResult<JsNumber> {
let scope = call.scope;
let a = call.arguments
.require(scope, 0)?
.check::<JsNumber>()?
.value();
let b = call.arguments
.require(scope, 1)?
.check::<JsNumber>()?
.value();
Ok(JsNumber::new(scope, a + b))
}
/// Takes in an object, returning a new object.
fn obj_adder(call: Call) -> JsResult<JsObject> {
use neon::js::Object;
let scope = call.scope;
let obj = &call.arguments.require(scope, 0)?.check::<JsObject>()?;
let a: f64 = obj.get(scope, "a")?.check::<JsNumber>()?.value();
let b: f64 = obj.get(scope, "b")?.check::<JsNumber>()?.value();
let result = JsObject::new(scope);
result.set("result", JsNumber::new(scope, a + b))?;
Ok(result)
}
register_module!(m, {
m.export("hello", hello)?;
m.export("adder", adder)?;
m.export("objAdder", obj_adder)?;
Ok(())
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment