gpt4 book ai didi

c++ - native Node.JS 模块 - 从参数解析 int[]

转载 作者:行者123 更新时间:2023-11-30 03:47:23 24 4
gpt4 key购买 nike

我正在尝试编写一个 native C++ 模块以包含在 Node.js 项目中——我遵循了指南 here并且设置得很好。

一般的想法是我想将一个整数数组传递给我的 C++ 模块进行排序;该模块然后返回排序后的数组。

但是,我无法使用 node-gyp build 进行编译,因为我遇到了以下错误:

error: no viable conversion from 'Local' to 'int *'

它在我的 C++ 中提示这段代码:

void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();

int* inputArray = args[0]; // <-- ERROR!

sort(inputArray, 0, sizeof(inputArray) - 1);

args.GetReturnValue().Set(inputArray);
}

这一切对我来说都是概念上的意义——编译器不能神奇地将 arg[0](大概是 v8::Local 类型)转换为 整数*。话虽如此,我似乎无法找到任何方法将我的参数成功转换为 C++ 整数数组。

应该知道,我的 C++ 相当生疏,而且我对 V8 几乎一无所知。谁能指出我正确的方向?

最佳答案

这不是微不足道的:您首先需要将 JS 数组(内部表示为 v8::Array)解压缩为可排序的东西(如 std::vector),对其进行排序,然后将其转换回来到 JS 数组。

这是一个例子:

void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();

// Make sure there is an argument.
if (args.Length() != 1) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Need an argument")));
return;
}

// Make sure it's an array.
if (! args[0]->IsArray()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "First argument needs to be an array")));
return;
}

// Unpack JS array into a std::vector
std::vector<int> values;
Local<Array> input = Local<Array>::Cast(args[0]);
unsigned int numValues = input->Length();
for (unsigned int i = 0; i < numValues; i++) {
values.push_back(input->Get(i)->NumberValue());
}

// Sort the vector.
std::sort(values.begin(), values.end());

// Create a new JS array from the vector.
Local<Array> result = Array::New(isolate);
for (unsigned int i = 0; i < numValues; i++ ) {
result->Set(i, Number::New(isolate, values[i]));
}

// Return it.
args.GetReturnValue().Set(result);
}

免责声明:我不是 v8 向导,也不是 C++ 向导,所以可能有更好的方法来做到这一点。

关于c++ - native Node.JS 模块 - 从参数解析 int[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33700969/

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