LoginSignup
20
18

More than 5 years have passed since last update.

node-gypを使ってnative addonを作成する (1) - Hello World

Last updated at Posted at 2014-07-26

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!

続きます

参考

20
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
18