Binary array using V8 engine

2019-05-29 05:15发布

I have an array of bytes defined as

unsigned char ptr = new unsigned char[1024];
fillWithSomething(ptr, 1024);

Then, I need to store the ptr variable in a Local< Array> variable of V8 Engine or another kind of V8 data type. Currently, I am converting the array of bytes into a string in order to store in a Local< String> variable, but this approach is inefficient to my application.

Thanks in advance.

UPDATED (thanks to Vyacheslav Egorov)

I test the solution with an external array but I can't use it on my node.js server code. I have the following code (on my extension side C++):

Handle<Object> array = Object::New();
array->SetIndexedPropertiesToExternalArrayData(getBytes(), kExternalUnsignedByteArray, bytesSize);
return array;

My question is, How I can use the array variable in my server code (javascript) to call the function GetIndexedPropertiesExternalArrayData().

Thanks again

2条回答
Anthone
2楼-- · 2019-05-29 05:53

like Vyacheslav Egorov already answered

  obj->SetIndexedPropertiesToExternalArrayData(data,
                                           kExternalUnsignedByteArray,
                                           length);

is the right answer. If you need more examples you can check out https://github.com/joyent/node they use lots of v8 functionallity.

just grep -nrw ".*SetIndexedPropertiesToExternalArrayData.*" "." in the /src folder of the project and you will get lots of examples for SetIndexedPropertiesToExternalArrayData

查看更多
Anthone
3楼-- · 2019-05-29 05:54

The most efficient way is to use external arrays:

v8::Handle<v8::Object> external_array = v8::Object::New();
external_array->SetIndexedPropertiesToExternalArrayData(ptr, v8::kExternalUnsignedByteArray, 1024);

Good example of external arrays API usage (including lifetime management) can be found in d8.cc: https://github.com/v8/v8/blob/7a0c55bd0d07135ce317f0e95909120eaafd5973/src/d8.cc#L394-L591

查看更多
登录 后发表回答