c++级nodeJS模块加载
C++ level nodeJS module loading
我正在开发一个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++级别的模块注入!
相关文章:
- 当我尝试加载内核模块时,如何修复C++中的这个 malloc() 错误?
- 如何在没有"路径"模块的情况下加载 cheerp-wasm 程序?
- 无法加载 QML 插件:无法保护模块,因为它从未注册过
- 如何在C++中获得预加载的模块名称
- 如果我想通过OpenCV dnn模块加载PyTorch的模型,我应该如何保存它
- 在FreesWitch中使用AWS C SDK加载模块时未定义的符号错误
- 在 Lua 中加载 C++ 模块时'Attempt to index a string value'错误
- 地址清理器和运行时加载动态库 ->(<未知模块>)
- 将所有模块加载到过程中,然后将其出口
- 保存和加载我的模块
- Visual Studio 在附加到进程时不会加载模块
- C# 无法加载 DLL(找不到模块结果:0x8007007E)
- 在模块加载/卸载时构造/破坏外部c++模块中的对象
- LD_PRELOAD应该加载模块还是只使用模块来替换符号
- Python C API-重新加载模块
- DLL 无法加载:0x8007007E找不到模块。不确定导致此依赖项问题的原因
- 加载程序如何从动态模块分配/取消分配静态数据
- 模块"MyShellExt.dll"加载失败
- 为什么要在运行时加载模块?
- LoopPass可加载模块的未定义符号