Node.js プラグインの作成 (6) - クラス オブジェクトをパラメーターとしてエクスポートする

以前の記事では、C++ を介して Node.js のカスタム クラス オブジェクトをエクスポートする方法を書きました。この記事では、このカスタム クラスの一部をさらに操作しました. この記事の目的は、エクスポートされたカスタム クラス オブジェクトを、エクスポートされた関数のパラメーターとして渡すことです。

関数の擬似コードは次のとおりです。

MyObject obj1=新しい MyObject(11); 

MyObject obj2=新しい MyObject(22);

Var ret=Add(obj1,obj2) ; //ここで重要なのは、追加するパラメータとして 2 つのオブジェクトを渡すことです。

プラグインの実装コードを書いてみよう

 プラグイン エクスポート クラスの C++ コード

  PassedObject.h 

//
// Created by usher.yue on 2021/12/31.
//
#ifndef MY_NODE_ADDON_PASSEDOBJECT_H
#define MY_NODE_ADDON_PASSEDOBJECT_H
#include <napi.h>


class PassedObject : public Napi::ObjectWrap<PassedObject> {
public:
    static Napi::Object Init(Napi::Env env, Napi::Object exports);
    double Val() const { return value_; }
    PassedObject(const Napi::CallbackInfo& info);
private:
    double value_;
};


#endif //MY_NODE_ADDON_PASSEDOBJECT_H

PassedObject.cpp

//
// Created by usher.yue on 2021/12/31.
//

#include "PassedObject.h"


Napi::Object PassedObject::Init(Napi::Env env, Napi::Object exports) {
    Napi::Function func =
            DefineClass(env,"MyObject",{});
    //自动消亡计数
    Napi::FunctionReference* constructor = new Napi::FunctionReference();
    //持久化func
    *constructor = Napi::Persistent(func);
    //设置上线文环境
    env.SetInstanceData(constructor);
    exports.Set("MyObject", constructor->Value());
    return exports;
}


/**
 * 初始化父类
 * @param info
 */
PassedObject::PassedObject(const Napi::CallbackInfo& info): Napi::ObjectWrap<PassedObject>(info) {
    Napi::Env env = info.Env();
    int length = info.Length();
    if (length <= 0 || !info[0].IsNumber()) {
        Napi::TypeError::New(env, "Number expected").ThrowAsJavaScriptException();
        return;
    }
    Napi::Number value = info[0].As<Napi::Number>();
    this->value_ = value.DoubleValue();
}

main.cpp コード

#include <napi.h>
#include "PassedObject.h"

//模块注册函数,用于每个自定义模块注册
Napi::Object Init(Napi::Env env, Napi::Object exports) {
    auto add = [&](const Napi::CallbackInfo &info) {
        Napi::Env env = info.Env();
        //解包参数1
        PassedObject *obj1 =
                Napi::ObjectWrap<PassedObject>::Unwrap(info[0].As<Napi::Object>());
        //解包参数2
        PassedObject *obj2 =
                Napi::ObjectWrap<PassedObject>::Unwrap(info[1].As<Napi::Object>());
        //相加结果
        double sum = obj1->Val() + obj2->Val();
        return Napi::Number::New(env, sum);
    };
    exports.Set("add", Napi::Function::New(env, add));
    return PassedObject::Init(env, exports);
}

NODE_API_MODULE(addon, Init)

binding.gyp 構成

{
  "targets": [
    {
      "target_name": "my_node_addon",
      "cflags!": [ "-fno-exceptions" ],
      "cflags_cc!": [ "-fno-exceptions" ],
      "sources": [ "main.cpp","PassedObject.cpp" ],
      "include_dirs": [
        "<!@(node -p \"require('node-addon-api').include\")"
      ],
      'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ],
    }
  ]
}

index.js コード

var addon = require('bindings')('my_node_addon.node');

//通过原型创建对象
var obj1 = new  addon.MyObject(10);
var obj2 = new  addon.MyObject(120);
//对象作为参数传递
let result=addon.add(obj1,obj2);
console.log(result);

プラグインをコンパイル

sudo env CC=Clang CXX=Clang++ node-gyp rebuild

出力は次のとおりです。

 

おすすめ

転載: blog.csdn.net/yue7603835/article/details/122256282