Click here to Skip to main content
15,069,665 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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)

C++
#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:

C++
#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.

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.
Posted
Comments
Stefan_Lang 25-May-21 4:09am
   
I'm not familiar with Node.js, but how can Napi::Float32Array::New() know about the size of the float array? Check the argument list expected by this function. I don't know anything about it, but I guess this function is used to create a container for an array of loat values, and that would require at the very least to pass the size of the required array, or alternatively pass an object that contains this info such as std::vector.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900