Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate a v8 array?

Tags:

c++

arrays

v8

I have a vector std::vector<std::string> path and I would like to copy it to a v8 array and return it from my function.

I have tried creating a new array

v8::Handle<v8::Array> result;

and putting the values from path into result but with no luck. I've also tried several variations of

return scope.Close(v8::Array::New(/* I've tried many things in here */));

without success.

This is a similar question but I cant seem to duplicate the results.

How do you populate v8 arrays?

like image 211
Loourr Avatar asked May 20 '13 01:05

Loourr


2 Answers

This example directly from the Embedder's Guide seems very close to what you want - replace new Integer objects with new String objects.

// This function returns a new array with three elements, x, y, and z.
Handle<Array> NewPointArray(int x, int y, int z) {

  // We will be creating temporary handles so we use a handle scope.
  HandleScope handle_scope;

  // Create a new empty array.
  Handle<Array> array = Array::New(3);

  // Return an empty result if there was an error creating the array.
  if (array.IsEmpty())
    return Handle<Array>();

  // Fill out the values
  array->Set(0, Integer::New(x));
  array->Set(1, Integer::New(y));
  array->Set(2, Integer::New(z));

  // Return the value through Close.
  return handle_scope.Close(array);
}

I'd read up on the semantics of Local and Persistent handles because I think that is where you have got stuck.

This line:

v8::Handle<v8::Array> result;

Doesn't create a new array - It only creates a Handle that can later be filled in with an array.

like image 93
mythagel Avatar answered Oct 20 '22 00:10

mythagel


To create a new array

    Handle<Array>postOrder = Array::New(isolate,5);
    //New takes two argument 1st one should be isolate and second one should 
    //be the number 

To Set the element in v8::array

    int elem = 101; // this could be a premitive data type, array or vector or list 
    for(int i=0;i<10;i++) {
      postOrder->Set(i++,Number::New(isolate,elem));
    } 

To Get the element from v8::array

    for(int i=0; i<postOrder->Length();i++){
       double val = postOrder->Get(i)->NumberValue()
    }

    //Type conversion is important in v8 to c++ back and forth; there is good library for data structure conversion; **V8pp Header only Librabry**

Thanks!!

like image 20
Parit Avatar answered Oct 19 '22 23:10

Parit