LoginSignup
4
3

More than 5 years have passed since last update.

Node.js v4.2.6 v8ライブラリ C++アドオンのAPIまとめ

Last updated at Posted at 2017-08-02

Node.js v4.2.6のC++アドオンに関してです。
UbuntsuにNode-REDをインストールしたら、Node.jsがv4.2.6になったのですが、そのバージョンのC++アドオン(v8)の技術情報が少ない上に、よくドキュメントから使用する関数を見つけにくかったのでまとめました。

Node.js バージョン確認方法

node -v
v4.2.6

関数の登録

NODE_SET_METHODの行を登録するAPIの数だけ並べます。

void Init(Local<Object> exports, Local<Object> module) {
    NODE_SET_METHOD(module, "test", test); // ""内はAPI名, 後ろは関数名
}

データの受け取り

関数の宣言

void test(const FunctionCallbackInfo<Value>& args) {
    ....
}

文字列 --> char の場合

const char* ToCString(const String::Utf8Value& value) {
    return *value ? *value : "<string conversion failed>";
}
void test(const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();
    String::Utf8Value str(args[0]);
    const char* str_char = ToCString(str);
    ....
}

文字列 --> v8:String の場合

void test(const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();
    String str = arg[0]->ToString();
    ....
}

Boolean の場合

void test(const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();
    Local<Boolean> obj = arg[0]->ToBoolean();
    ....
}

数値の場合

void test(const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();
    double value = arg[0]->NumberValue();
    ....
}

値の代入方法

Local<String> str = String::NewFromUtf8(isolate, "hello");     // 文字列
Local<Number> num = Number::New(isolate, 10);     // 数値
Local<Boolean> boo = Boolean::New(isolate, true);     // bool

戻り値

戻り値は、args.GetReturnValue()で返します。

数字

  Local<Number> double_num = Number::New(isolate, value);    // double型
  Local<Number> int_num = Integer::New(isolate, value);      // integer型
  args.GetReturnValue().Set(double_num);

文字列

  args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world"));

JSON

  Local<Object> obj = Object::New(isolate);
  obj->Set(String::NewFromUtf8(isolate, "msg"), String::NewFromUtf8(isolate, "hello world"));
  args.GetReturnValue().Set(obj);

エラーを返す

if(!args[0]->IsString()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate,"args must be string")));
    return;
}

関数を登録する

void Init(v8::Local<v8::Object> exports){
    NODE_SET_METHOD(exports, "func1", func1);
    NODE_SET_METHOD(exports, "func2", func2);
}

こうすると、nodejsではこのように呼び出すことができます。


var addon = require('./build/Release/addon');
addon.func1(xxx);
addon.func2(xxx);
4
3
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
4
3