c++级nodeJS模块加载

C++ level nodeJS module loading

本文关键字:加载 模块 nodeJS c++      更新时间:2023-10-16

我正在开发一个NodeJS模块,它的文件大小正在急剧增加,但是我已经意识到我可以将我的模块分为两个独立的模块。当这种情况发生时,只有第二个模块中的几个函数需要使用第一个模块的内部c++类。有没有可能只把第一个模块的原型传递给第二个模块?

的例子:

模块:有一个类叫做cModuleA:

class cModuleA {
    //declarations
    data* pointer;
}

模块B :有大约100个函数,但其中只有一个需要操作data*指针。它还需要返回cModuleA对象(因此它需要cModuleA的原型或意识到cModuleA的实现)

我试图从第一个模块(dllimport/dllexport在windows)导出符号,但我只是想知道是否有更好的选择注入依赖在c++级别。

我找到了这个问题的解决方案,我将详细介绍它,因为可能没有人试图做这样疯狂的事情!

假设有两个本地节点模块。这意味着它们存在于单独的可执行文件(.node)中。其中一个是模块a,另一个是模块b:

ModuleA :

class cppClass
{
public:
    cppClass();
    ~cppClass();
    // C++ stuff here
}; // !class cppClass
class cppClassWrap
    : public node::ObjectWrap
{
public:
    // used for initializing this class for Node/v8
    static void Initialize(v8::Handle<Object> target);
    // internal C++ data accessor
    cppClass* GetWrapped() const { return internal_; };
    // internal C++ data accessor
    void SetWrapped(cppClass* n)  { internal_ = n; };
private:
    cppClassWrap();
    cppClassWrap(cppClass*);
    ~cppClassWrap() { if (internal_) delete internal_; };
    // JS stuff here
    static Persistent<Function> constructor;
    // JS c'tor
    static NAN_METHOD(New);
    // internal C++ data
    cppClass* internal_;
}; // !class cppClassWrap
//-------------------------------------------------
// JS c'tor implementation
NAN_METHOD(cppClassWrap::New)
{
    NanScope();
    cppClassWrap* obj;
    if (args.Length() == 0)
    {
        obj = new cppClass();
    }
    // **** NOTICE THIS! ****
    // This is a special case when in JS land we initialize our class like: new cppClassWrap(null)
    // It constructs the object with a pointer, pointing to nothing!
    else if (args[0]->IsNull())
    {
        obj = new cppClass(nullptr);
    }
    else
    {
        //copy constructor for the JS side
        obj = new cppClassWrap(ObjectWrap::Unwrap<cppClassWrap>(args[0]->ToObject())->GetWrapped());
    }
    obj->Wrap(args.This());
    NanReturnValue(args.This());
}
从这里开始,您所需要做的就是在ModuleB中使用Persistent句柄来存储ModuleA的类c'tor的构造函数的副本。例如,你可以有一个叫做dependencies的方法,在JS中像这样调用它:
var cppClassWrap = require("ModuleA.node").cppClassWrap;
var moduleB = require("ModuleB.node").dependencies({
    "moduleA" : function() {return new cppClassWrap(null); }
});

和完成了!你有c++级别的模块注入!