nodejs c++ 写模块调用js函数函数有两个int参数
以下是一个示例,展示如何在C++模块中调用JavaScript函数,该函数有两个int参数:
#include <node.h>
using namespace v8;
// 定义一个C++函数,用于调用JavaScript函数
void CallJsFunction(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
// 检查参数数量是否正确
if (args.Length() < 3) {
isolate->ThrowException(
Exception::TypeError(String::NewFromUtf8(isolate, "参数数量不正确")));
return;
}
// 将第一个和第二个参数转换为int
int a = args[0]->Int32Value();
int b = args[1]->Int32Value();
// 获取全局的上下文
Local<Context> context = isolate->GetCurrentContext();
// 获取JavaScript函数
Local<Function> func = Local<Function>::Cast(args[2]);
// 构造参数列表
Local<Value> argv[2] = {
Integer::New(isolate, a),
Integer::New(isolate, b)
};
// 调用JavaScript函数
Local<Value> result = func->Call(context, context->Global(), 2, argv).ToLocalChecked();
// 返回结果
args.GetReturnValue().Set(result);
}
// 初始化模块
void Init(Local<Object> exports) {
NODE_SET_METHOD(exports, "callJsFunction", CallJsFunction);
}
// 将模块定义为一个Node.js模块
NODE_MODULE(NODE_GYP_MODULE_NAME, Init)
在JavaScript中,可以像这样调用该函数:
const addon = require('./build/Release/addon');
function myFunc(a, b) {
return a + b;
}
const result = addon.callJsFunction(1, 2, myFunc);
console.log(result); // 输出3
``
原文地址: https://www.cveoy.top/t/topic/fJXL 著作权归作者所有。请勿转载和采集!