Native Node.JS模块 – 从参数中parsingint

我正在尝试编写一个本地C ++模块来包含在一个Node.js项目中 – 我遵循这里的指南,并且设置得非常好。

总的想法是,我想要传递一个整数数组到我的C ++模块进行sorting; 该模块然后返回sorting的数组。

但是,我不能编译使用node-gyp build因为我遇到以下错误:

错误:没有可行的从“本地”转换为“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] (大概是typesv8::Local )转换成int* 。 话虽如此,我似乎无法find任何方法让我的参数成功转换成一个C + +整数数组。

应该知道,我的C ++是相当生锈的,我对V8一无所知。 任何人都可以指向正确的方向吗?

这不是微不足道的:你首先需要解压JS数组(内部表示为一个v8::Array ),将其sorting(如std::vector ),对其进行sorting并将其转换回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 ++的,所以可能有更好的方法来做到这一点。