Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use nan to receive and return Float32Array in an addon

I'm trying to use nan in order to calculate something on an array of floats in an add-on and then return it as a Float32Array.

But while the args have IsNumber() and NumberValue()functions it only has a IsFloat32Array() function and no Float32Array().

I've tried to look at those: 1,2 tutorials but found no suitable examples.

NAN_METHOD(Calc) {
  NanScope();

  if (args.Length() < 2) {
    NanThrowTypeError("Wrong number of arguments");
    NanReturnUndefined();
  }

  if (!args[0]->IsNumber() || !args[1]->IsFloat32Array()) {
    NanThrowTypeError("Wrong arguments");
    NanReturnUndefined();
  }
  /* a vector of floats ? */  args[0]-> ???;
  double arg1 = args[1]->NumberValue();
  // some calculation on the vector

  NanReturnValue(/* Return as a Float32Array array */);
}
like image 373
Darius Avatar asked Nov 01 '22 03:11

Darius


1 Answers

Accepting a TypedArray is best done with Nan::TypedArrayContents

Local<TypedArray> ta = args[0].As<TypedArray>();
Nan::TypedArrayContents<float> vfloat(ta);
float firstElement = (*vfloat)[0];

There is no NAN helper for constructing a typed array yet, but I use this helper in my own code:

template <typename T> struct V8TypedArrayTraits; // no generic case
template<> struct V8TypedArrayTraits<Float32Array> { typedef float value_type; };
template<> struct V8TypedArrayTraits<Float64Array> { typedef double value_type; };
// etc. v8 doesn't export anything to make this nice.

template <typename T>
Local<T> createTypedArray(size_t size) {
  size_t byteLength = size * sizeof(typename V8TypedArrayTraits<T>::value_type);
  Local<ArrayBuffer> buffer = ArrayBuffer::New(Isolate::GetCurrent(), byteLength);
  Local<T> result = T::New(buffer, 0, size);
  return result;
};
like image 115
ZachB Avatar answered Nov 12 '22 19:11

ZachB