Native Node.JS模块-解析参数中的int[]
Native Node.JS module - parsing an int[] from arguments
我正在尝试编写一个本机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++向导,所以可能有更好的方法可以做到这一点。
相关文章:
- 类型为 "int*" 的参数与 C++ 中错误类型"int**"参数不兼容
- 为表示一个或多个操作的C++函数的int参数寻找类型安全的替换
- 为什么SDL_QueryTexture不为其 int* 参数赋值?
- 如何增加模板类型 int 参数?
- 如何将INT参数放入C 中的Sigleton构造器中
- 如何使用 int 参数循环访问模板函数
- 是否可以使用C 函数中的const int参数创建数组
- 在与时间一起使用 srand 时,如果我没有time_t参数明确地将参数转换为无符号的 int 参数,这有关系吗?
- 带有unsigned int参数的C++函数在使用negative调用它时会得到奇怪的结果
- 是一个与int[]参数完全相同的int*参数
- 我们可以将所有"int"参数和返回类型替换为 DllImport 方法签名中的"IntPtr"吗?
- 字符串和int参数出现C++编译器错误
- 模板int参数来自C++11中的常量表达式
- 避免使用int参数的模板类的C++爆炸性实例化
- 我们可以创建临时传入的"std::vector<int>"参数吗?
- 如何使用QT5中的lambdas将具有int参数的信号连接到具有枚举参数with的插槽
- 将指向函数的指针数组作为"int"参数传递是否可以将地址转换为整数?
- 为什么系统在没有警告的情况下接受作为int参数传递的long int
- 使用 int&& 参数通过 int&& 进行函数初始化
- 成员函数的Boost线程int参数不工作