Skip to content

Instantly share code, notes, and snippets.

@mafintosh
Created November 28, 2017 18:47
Show Gist options
  • Save mafintosh/3d4794fa5077268dd48cb41e54f2ddc3 to your computer and use it in GitHub Desktop.
Save mafintosh/3d4794fa5077268dd48cb41e54f2ddc3 to your computer and use it in GitHub Desktop.
Write native modules like you write C
#include <nan.h>
using namespace v8;
typedef struct {
int result;
int prev;
} fibo_t;
NAN_METHOD(Init) {
fibo_t *self = (fibo_t *) node::Buffer::Data(info[0]->ToObject());
self->result = 1;
self->prev = 0;
}
NAN_METHOD(Next) {
fibo_t *self = (fibo_t *) node::Buffer::Data(info[0]->ToObject());
int result = self->result;
self->result = result + self->prev;
self->prev = result;
info.GetReturnValue().Set(Nan::New(result));
}
NAN_MODULE_INIT(InitAll) {
Nan::Set(target, Nan::New<String>("SIZEOF_FIBO").ToLocalChecked(), Nan::New<Number>(sizeof(fibo_t)));
Nan::Set(target, Nan::New<String>("init").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(Init)).ToLocalChecked());
Nan::Set(target, Nan::New<String>("next").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(Next)).ToLocalChecked());
}
NODE_MODULE(c_ish, InitAll)
var fibo = require('./')
var struct = Buffer.allocUnsafe(fibo.SIZEOF_FIBO)
fibo.init(struct)
for (var i = 0; i < 10; i++) {
console.log(fibo.next(struct))
}
var binding = require('node-gyp-build')(__dirname)
module.exports = binding
{
"name": "c-ish",
"version": "0.0.0",
"description": "WIP - nothing to see here",
"main": "index.js",
"dependencies": {
"nan": "^2.8.0",
"node-gyp-build": "^3.2.2"
},
"devDependencies": {},
"repository": {
"type": "git",
"url": "https://github.com/mafintosh/c-ish.git"
},
"author": "Mathias Buus (@mafintosh)",
"license": "MIT",
"bugs": {
"url": "https://github.com/mafintosh/c-ish/issues"
},
"homepage": "https://github.com/mafintosh/c-ish"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment