Node.jsのaddonの作成をするためにはnode-gypを使う。
$ npm install -g node-gyp
Hello World
module.exports.hello = function() { return 'world'; }
と同じものをaddonで作る。
hello.cc
# include <node.h>
# include <v8.h>
using namespace v8;
Handle<Value> Hello(const Arguments& args) {
HandleScope scope;
return scope.Close(String::New("Hello World!"));
}
void init(Handle<Object> exports) {
exports->Set(String::NewSymbol("hello"),
FunctionTemplate::New(Hello)->GetFunction());
}
NODE_MODULE(addon, init) // 後ろにセミコロンいらない
NODE_MODULE
の後ろにセミコロンはいらない。
次に、hello.cc
をビルドするためにbinding.gyp
を用意する。
binding.gyp
{
"targets": [
{
"target_name": "addon",
"sources": [
"hello.cc"
]
}
]
}
次に node-gyp configure
で
現在のプラットフォーム用のビルドファイルを作る。
その後にnode-gyp build
を行う。
-
node-gyp clean
-- ビルドディレクトリの削除 -
node-gyp configure
-- ビルドファイルの生成 -
node-gyp build
-- ビルドの実行
$ node-gyp clean configure build
$ node-gyp rebuild # 上といっしょ
するとbuild/Release/hello.node
が作られる
hello.js
var addon = require('./build/Release/addon');
console.log( addon.hello() ); // Hello World!