Native Node.JS模块-解析参数中的int[]

Native Node.JS module - parsing an int[] from arguments

本文关键字:int 参数 JS Node 模块 Native      更新时间:2023-10-16

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

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

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

错误:没有从"Local"到"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类型)转换为int*。话虽如此,我似乎找不到任何方法将我的参数成功地转换为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++向导,所以可能有更好的方法可以做到这一点。