Nodejs c++插件:无法访问Array元素



我想访问一个数组的元素,它作为一个参数从js端传递给函数。代码如下:

void Method(const FunctionCallbackInfo<Value> &args){
Isolate* isolate = args.GetIsolate();
Local<Array> array = Local<Array>::Cast(args[0]);
for(int i=0;i<(int)array->Length();i++){
auto ele = array->Get(i);
}

我得到这个错误:

error: no matching function for call to ‘v8::Array::Get(int&)’

在阅读V8数组的实现后,我知道Array没有Get方法。

下面是Array的实现在v8源代码中:
class V8_EXPORT Array : public Object {
public:
uint32_t Length() const;
/**
* Creates a JavaScript array with the given length. If the length
* is negative the returned array will have length 0.
*/
static Local<Array> New(Isolate* isolate, int length = 0);
/**
* Creates a JavaScript array out of a Local<Value> array in C++
* with a known length.
*/
static Local<Array> New(Isolate* isolate, Local<Value>* elements,
size_t length);
V8_INLINE static Array* Cast(Value* obj);
private:
Array();
static void CheckCast(Value* obj);
};

我是v8 lib的新手。我通过了一些教程,这对他们来说很好。谁能帮我弄清楚它有什么毛病吗?如果我们不能使用Local<Array>,那么还有什么可以达到这个目的呢?

在不知道您针对的是哪个v8确切版本的情况下很难回答,但在当前的氧气文档中,v8::Object::Get有两个过载:

MaybeLocal< Value >     Get (Local< Context > context, Local< Value > key)
MaybeLocal< Value >     Get (Local< Context > context, uint32_t index)

所以我认为你可以这样做:

Local<Context> ctx = isolate->GetCurrentContext();
auto ele = array->Get(ctx, i);
...

最新更新