Node.js C++ 使用 vector 存放函数类型并判断重复
Node.js C++ 使用 vector 存放函数类型并判断重复
本文介绍了如何在 Node.js C++ 扩展中使用 std::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
代码解释
- 定义函数类型
Function为std::function<void()>,表示无参数无返回值的函数类型。 - 使用
std::vector<Function>存放函数类型,名为functionVector。 AddFunction函数接收一个 JavaScript 函数作为参数,将其转换为std::function类型并添加到functionVector中。- 在添加函数之前,使用循环遍历
functionVector,判断函数是否已存在。如果存在,则删除重复的函数。 - 最后,将 JavaScript 函数转换为
std::function类型并添加到functionVector中。
总结
本文提供了一种在 Node.js C++ 扩展中使用 std::vector 存放函数类型并判断重复的方法。该方法简单易懂,可用于管理和维护函数集合。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/olSe 著作权归作者所有。请勿转载和采集!