I am trying to run c++ in node.js using node-addon-api.
I've read one well-written elaborate article from medium.
But I want to pass to one of my functions a float, and a float array to another function.
I want to return a float array from both of them.
The example of a function (greeting.cpp
)
#include <iostream>
#include <string>
#include <cmath>
#include "greeting.h"
float* helloUser( float name ) {
float* result = new float[3];
result[0] = 1;
result[1] = 2;
result[2] = name;
return result;
}
And the code of index.cpp
with a native implementation of the module:
#include <napi.h>
#include <string>
#include "greeting.h"
Napi::Float32Array greetHello(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
float user = (float) info[0].ToNumber();
float* result = helloUser( user );
return Napi::Float32Array::New(env, result);
}
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set(
Napi::String::New(env, "greetHello"), // property name => "greetHello"
Napi::Function::New(env, greetHello) // property value => `greetHello` function
);
return exports;
}
NODE_API_MODULE(greet, Init)
The thing is, Napi::Float32Array
doesn't work, I tried Napi::TypedArrayOf<float>
, it doesn't work either. I am not that much into writing modules.
I just want my pure c++ code running in node to send its result to the frontend.
I tried accepting and returning floats with Napi::Number
and it works fine.
But I have no clue how to get it start working with arrays.
Any help is appreciated.
I ran into a similar issue and the Napi instance methods expect either a:
or
Even though
Napi::TypedArray
inherits fromNapi::Object
which inherits fromNapi::Value
, it turns out you have to explicitly return aNapi::Value
as follows:Which will get you a
Float32Array
: