gpt4 book ai didi

c++ - 从nodejs获取c++中的参数

转载 作者:行者123 更新时间:2023-12-05 06:57:08 27 4
gpt4 key购买 nike

我正在尝试在 C++ 中构建 nthRoot 函数,然后将其嵌入到我的 Node js 项目中。

问题是网络上的所有教程都是针对旧的 v8 版本的,在 Node 12+ 中不起作用

我不是c++程序员

#include <node.h>
#include <iostream>


using namespace v8;
using namespace std;


double NthRoot(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
int n = args[0]->IntegerValue();
double degree = args[1]->DoubleValue();

double result = std::pow(n, 1.0/degree);

args.GetReturnValue().Set(result);

}

void Initialize(Local<Object> exports) {
NODE_SET_METHOD(exports, "nthroot", NthRoot);
}

NODE_MODULE(addon, Initialize);

最佳答案

最终使用了 napi


#include <napi.h>

Napi::Value NthRoot(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();

if (info.Length() < 2) {
Napi::TypeError::New(env, "Wrong number of arguments")
.ThrowAsJavaScriptException();
return env.Null();
}

if (!info[0].IsNumber() || !info[1].IsNumber()) {
Napi::TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException();
return env.Null();
}

double arg0 = info[0].As<Napi::Number>().DoubleValue();
double arg1 = info[1].As<Napi::Number>().DoubleValue();
Napi::Number num = Napi::Number::New(env, pow(arg0,1.0/arg1));

return num;
}

Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "nthroot"), Napi::Function::New(env, NthRoot));
return exports;
}

NODE_API_MODULE(cMath, Init)

关于c++ - 从nodejs获取c++中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64964425/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com