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 */);
}
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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With