Created
November 28, 2017 18:47
-
-
Save mafintosh/3d4794fa5077268dd48cb41e54f2ddc3 to your computer and use it in GitHub Desktop.
Write native modules like you write C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var binding = require('node-gyp-build')(__dirname) | |
module.exports = binding |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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