使用C++插件调用Require

top*_*erg 2 c++ add-on node.js requirejs

在编写C++ Node.JS Addon时,有什么require('./someModule')能够加载模块以便在编译的Addon中使用?

我找到了这个方法:

Handle<String> source = 
    String::New("NameOfLibrary.register(require('./someModule'))");
Handle<Script> script = 
    Script::Compile(source);
script->Run();
Run Code Online (Sandbox Code Playgroud)

如果与我在这里提出的问题一起使用会很好地工作,但我想知道是否有更原生的方式.

log*_*yth 6

您应该能够在初始化函数中访问标准模块require函数.一般来说,我只是从那里调用它,因为懒惰的调用require不是一个好主意,因为它们是同步的.

static void init (Handle<Object> target, Handle<Object> module) {
    HandleScope scope;
    Local<Function> require = Local<Function>::Cast(
        module->Get(String::NewSymbol("require")));

    Local<Value> args[] = {
        String::New("./someModule")
    };
    Local<Value> someModule = require->Call(module, 1, args);

    // Do whatever with the module
}


NODE_MODULE(module_file_name, init);
Run Code Online (Sandbox Code Playgroud)