0

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?

1 Answer 1

2

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);
...
Sign up to request clarification or add additional context in comments.

2 Comments

It worked! Thank you so much. Do you know some good resources for node addon reference? I'm following this tutorial series nodeaddons.com/c-processing-from-node-js. It is beginner-friendly but it's using an older version.
I just looked at the API documentation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.