Ælex Ælex - 2 months ago 17
Node.js Question

Populating a Node v8 Float32Array from C++

I've looked into the documentation:



I am trying to populate a v8 array of floats, using a
thrust::host_vectofr<float>
, where
dataset[i].vector = thrust::host_vector<float>


Using an Array, seems to be rounding to integers:

Local<Object> obj = Object::New(isolate);
Local<Array> vec = Array::New(isolate, dataset[i].vector.size());

// populate the v8 array (copy)
for (unsigned int k = 0; k < dataset[i].vector.size(); k++)
vec->Set(k, Number::New(isolate, dataset[i].vector[k]));

obj->Set(String::NewFromUtf8(isolate, "vector"), vec);


Using a typed array, the
Float32Array
:

Local<Object> obj = Object::New(isolate);
auto vec = Float32Array::New(ArrayBuffer::New(isolate, sizeof(float)), 0, dataset[i].vector.size());

// populate the v8 array (copy)
for (unsigned int k = 0; k < dataset[i].vector.size(); k++)
vec->Set(k, Number::New(isolate, dataset[i].vector[k]));

obj->Set(String::NewFromUtf8(isolate, "vector"), vec);


Compiles fine, but when executing it crashes:

*** Error in `node': corrupted double-linked list: 0x000000000734bf50 ***
fish: “node run.js” terminated by signal SIGABRT (Abort)


What is the correct approach to allocating and then populating a v8 Float32Array from C++, so that it can be used in JavaScript?

I also understand that Node.JS/v8 does not come with a
float
?

Answer

I'm not sure what version of V8 that is (calling Set without a context isn't in the API docs I see), but on 4.10, this works fine:

auto arr = v8::Array::New(isolate);
(void)arr->Set(context, 0, v8::Number::New(isolate, 2.5));
auto number = arr->Get(context, 0);
printf("%s\n", *v8::String::Utf8Value(number.ToLocalChecked()));

prints out

2.5

Converting it to a floating point value also works:

printf("%f\n", ((v8::Number*)*number.ToLocalChecked())->Value());
Comments