Node.js C++ 模块:使用 std::vector 存储 Local<Function> 并删除指定函数
Node.js C++ 模块:使用 std::vector 存储 Local 并删除指定函数
这是一个简单的例子,演示如何在 Node.js 中创建 C++ 模块并使用 std::vector 存储 Local
#include <node.h>
#include <vector>
using v8::Function;
using v8::Local;
using v8::Object;
using v8::Value;
std::vector<Local<Function>> functions;
void addFunction(const v8::FunctionCallbackInfo<Value>& args) {
Local<Function> func = Local<Function>::Cast(args[0]);
functions.push_back(func);
}
void removeFunction(const v8::FunctionCallbackInfo<Value>& args) {
Local<Function> func = Local<Function>::Cast(args[0]);
for (auto it = functions.begin(); it != functions.end(); ++it) {
if ((*it) == func) {
functions.erase(it);
break;
}
}
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "addFunction", addFunction);
NODE_SET_METHOD(exports, "removeFunction", removeFunction);
}
NODE_MODULE(NODE_GYP_MODULE_NAME, init)
在这个例子中,我们定义了两个函数 addFunction 和 removeFunction,它们分别用于添加和删除 LocaladdFunction 函数中,我们将传递给函数的参数转换为 LocalremoveFunction 函数中,我们遍历 std::vector,查找与传递给函数的参数相匹配的 Local
最后,我们使用 NODE_MODULE 宏将模块初始化函数导出为一个 Node.js 模块。通过这样做,我们可以在 JavaScript 中使用这些函数,例如:
const myModule = require('./build/Release/myModule');
function myFunction1() {
console.log('myFunction1 called');
}
function myFunction2() {
console.log('myFunction2 called');
}
myModule.addFunction(myFunction1);
myModule.addFunction(myFunction2);
// ...
myModule.removeFunction(myFunction1);
在这个例子中,我们首先将 myFunction1 和 myFunction2 添加到 C++ 模块中,然后在某个时刻将 myFunction1 从 C++ 模块中删除。
原文地址: https://www.cveoy.top/t/topic/oobb 著作权归作者所有。请勿转载和采集!