How to return float32 array from c++ in node-addon-api?

1.5k Views Asked by At

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.

1

There are 1 best solutions below

0
On

I ran into a similar issue and the Napi instance methods expect either a:

void MethodName(const Napi::CallbackInfo& info);

or

Napi::Value MethodName(const Napi::CallbackInfo& info);

Even though Napi::TypedArray inherits from Napi::Object which inherits from Napi::Value, it turns out you have to explicitly return a Napi::Value as follows:

Napi::Value greetHello(Napi::CallbackInfo const& info)
{
  Napi::Float32Array arr = Napi::Float32Array::New(info.Env(), 16);
  arr[0] = 1;
  arr[15] = 16;
  return arr;
}

Which will get you a Float32Array:

{
  greetHello: [Function (anonymous)]
}
Float32Array(16) [
  1, 0, 0,  0, 0, 0,
  0, 0, 0,  0, 0, 0,
  0, 0, 0, 16
]