我正在开发一个 NodeJS 模块,它的文件大小正在急剧增加,但是我意识到我可以将我的模块分成两个单独的模块。当这种情况发生时,我的第二个模块中只有少数函数需要使用我的第一个模块的内部 C++ 类。是否有可能以某种方式只将第一个模块的原型(prototype)传递给第二个模块?
例子:
模块 A:
有一个名为 cModuleA
的类:
class cModuleA {
//declarations
data* pointer;
}
模块 B:
有大约 100 个函数,但只有其中一个需要操作 data*
指针。它还需要返回 cModuleA
对象(因此它需要 cModuleA
的原型(prototype)或了解 cModuleA
实现)
我尝试从第一个模块(Windows 中的 dllimport/dllexport
)导出符号,但我只是想知道是否有更好的选择来在 C++ 级别注入(inject)依赖项。
最佳答案
我找到了这个问题的解决方案,我将详细介绍它,因为可能没有其他人尝试过做这样疯狂的事情!
假设您有两个 native Node 模块。这意味着它们存在于单独的可执行文件 (.node) 中。其中一个是moduleA,另一个是moduleB:
模块A:
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());
}
从现在开始,您需要做的就是例如拥有 Persistent
处理 ModuleB
存储 ModuleA
的构造函数的拷贝它的类主任。例如,您可以有一个名为 dependencies
的方法并在 JS 中调用它:
var cppClassWrap = require("ModuleA.node").cppClassWrap;
var moduleB = require("ModuleB.node").dependencies({
"moduleA" : function() {return new cppClassWrap(null); }
});
完成了!你有 C++ 级别的模块注入(inject)!
关于javascript - C++ 级别的 nodeJS 模块加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25235465/