nodejs c++ vector存放函数类型遍历vector判断另外一个函数是否已经存在vector如果存在就删除
可以使用以下代码实现:
#include <node.h>
#include <vector>
using namespace v8;
// 定义函数类型
typedef std::function<void()> Function;
// 存放函数类型的 vector
std::vector<Function> functionVector;
// 添加函数到 vector
void AddFunction(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
Local<Function> func = Local<Function>::Cast(args[0]);
// 将函数类型转为 std::function
Function function = [=]() {
Local<Value> result = func->CallAsFunction(isolate->GetCurrentContext(), Null(isolate), 0, nullptr).ToLocalChecked();
if (!result->IsUndefined()) {
String::Utf8Value str(isolate, result);
printf("%s\n", *str);
}
};
// 判断函数是否已存在于 vector 中
bool isExist = false;
for (auto iter = functionVector.begin(); iter != functionVector.end();) {
if (&(*iter) == &function) {
isExist = true;
iter = functionVector.erase(iter);
} else {
++iter;
}
}
// 如果不存在,则添加到 vector 中
if (!isExist) {
functionVector.push_back(function);
}
args.GetReturnValue().SetUndefined();
}
// 初始化模块
void Init(Local<Object> exports) {
NODE_SET_METHOD(exports, "addFunction", AddFunction);
}
NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
在 JavaScript 中使用:
const addon = require('bindings')('addon');
function foo() {
console.log('foo');
}
function bar() {
console.log('bar');
}
addon.addFunction(foo);
addon.addFunction(bar);
addon.addFunction(foo);
// 输出:
// foo
// bar
``
原文地址: https://www.cveoy.top/t/topic/fF4k 著作权归作者所有。请勿转载和采集!