4

I'd like to make use of the V8 Float32Array data structure. How can I initialise it?

I'd also be interested in direct memory access to the data. How could that be done?

ZachB
  • 13,051
  • 4
  • 61
  • 89
user1315172
  • 147
  • 3
  • 9
  • I have based my attempt so far on: http://nodejs.org/api/addons.html. `void ReadTypedArray(const FunctionCallbackInfo& args) { cout << "args.length " << (args.Length()); }` And I'm having trouble formatting the comment on stackoverflow because when I press return it saves the comment. – user1315172 Feb 18 '15 at 14:13
  • Previously I have read node buffers as char arrays using `unsigned char* jpeg_input_buffer = (unsigned char*)Buffer::Data(arg0);` – user1315172 Feb 18 '15 at 14:16
  • do you use node or pure v8? – vkurchatkin Feb 18 '15 at 14:17
  • I'm calling C++ code, using node. I am `using namespace v8;`, and I have `#include ` – user1315172 Feb 18 '15 at 14:24
  • I just tried `Float32Array arr = args[0]->Float32ArrayValue();`. It did not work. – user1315172 Feb 19 '15 at 08:35

1 Answers1

6

Updated

The best way now is to use the helper Nan::TypedArrayContents.

assert(args[i]->IsFloat32Array());
Local<Float32Array> myarr = args[i].As<Float32Array>();
Nan::TypedArrayContents<float> dest(myarr);
// Now use dest, e.g. (*dest)[0]

There's a good example of this in node-canvas.


Original Answer, which shows why the helper is useful

The v8 API is changing rapidly right now so this depends on your version of node/io.js. To access the data from the array provided as an argument, this should work for node 0.12 through io.js <3.0:

assert(args[i]->IsFloat32Array()); // These type-check methods are available.
Local<Float32Array> myarr = args[i].As<Float32Array>();
void* dataPtr = myarr->GetIndexedPropertiesExternalArrayData();

In io.js >=3.0 (v8 4.3) you should instead use ArrayBuffer::GetContents. (I haven't used this yet and will update this when 3.0 is released.) Docs are here.

In node 0.10, TypedArrays were home-brewed. This was one way of doing it:

Local<Object> buffer = args[i]->Get(NanNew("buffer"))->ToObject();
void* dataPtr = buffer->GetPointerFromInternalField(0);

Constructing a typed array can be done with:

 Float32Array::New(ArrayBuffer::New(Isolate::GetCurrent(), size * 4), 0, size);
ZachB
  • 13,051
  • 4
  • 61
  • 89