Use nan to get and return Float32Array in addon

I am trying to use nan to compute something on an array of floats in an add-in and then return it as a Float32Array

.

But while args has functions IsNumber()

and NumberValue()

, it only has function IsFloat32Array()

and no Float32Array()

.

I tried looking at them: 1 , 2 , but couldn't find any 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 */);
}

      

+3


source to share


1 answer


Adopting 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 building a typed array, 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;
};

      

0


source







All Articles