I am trying to run c++ in node.js using node-addon-api (as they say it is the simplest way).
And I want to pass a float array to my function.
I want to return a float array from it.
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"), Napi::Function::New(env, greetHello) );
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.
You can see my project here: github.com/agt-ru/cone3d
There I use c++ to make some calculations for the frontend.
But because I have not yet found a way to return an array, I return a string and then parse it in JS. And it's obviously defeats the whole purpose of writing c++ in the first place.
What I have tried:
I tried reading tutorials on node-addon-api, nan and have seen several youtube tutorials, but they are either too complex for the beginner or do not work or are lacking some important explanations.