gpt4 book ai didi

c++ - Node.js C++ Addon - 设置数组的特定索引

转载 作者:行者123 更新时间:2023-11-28 05:11:34 27 4
gpt4 key购买 nike

我正在尝试创建一个 Node.js C++ 插件来生成斐波那契数列以将其速度与普通 Node.js 模块进行比较,但我在设置数组的某个索引时遇到了问题。到目前为止我已经知道了:

#include <node.h>

namespace demo {

using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::Value;
using v8::Number;
using v8::Array;

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

int next, first = 0, second = 0, c = 0, n = args[0]->NumberValue();
Local<Array> arr = Array::New(isolate, n);

for (; c < n; c++) {
if ( c <= 1 ) next = c;
else {
next = first + second;
first = second;
second = next;
}
// How to set arr[c]?????
}

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

void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "fib", Method);
}

NODE_MODULE(addon, init)

}

第26行,arr[c]应该怎么设置? v8:Array 不提供下标运算符。

最佳答案

how should I set arr[c]? v8:Array doesn't provide a subscript operator.

它不是,但是 v8::Array 已经从 v8::Object 继承了函数成员 Set ,带有一个以整数 (uint32_t) 作为键的重载。用它来填充数组的每个元素:

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

int next, first = 0, second = 0, c = 0, n = args[0]->NumberValue();
Local<Array> arr = Array::New(isolate, n);

int i = 0;
for (; c < n; c++) {
if ( c <= 1 ) next = c;
else {
next = first + second;
first = second;
second = next;
}
arr->Set(i++, Number::New(isolate, next));
}

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

关于c++ - Node.js C++ Addon - 设置数组的特定索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43401843/

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