Search code examples
c++node.jsarraysv8node-gyp

Nodejs c++ addon: Not able to access Array elements


I want to access the elements of an array that is passed in a function as an arg from the js side. The code is like this:

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);
    }

I'm getting this error:

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

After reading the implementation of the V8 Array and I get to know that there is no Get method for Array.

Here is the implementation of Array in the v8 source code:

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);
};

I'm new to v8 lib. I walked through some tutorials and it was working fine for them. Can anyone help me to figure out what's wrong with it? If we can't use Local<Array> then what else is there which can fulfill this purpose?


Solution

  • Hard to answer without knowing which exact version of v8 you're targeting, but in the current doxygen documentation there are two overloads for v8::Object::Get:

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

    So I think you can do the following:

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