Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node-Addon-Api Pass Array As Function Argument

I am trying to create a basic native node addon where a javascript array is passed from node and then processed in c++. The problem is I cannot figure out how to correctly pass the array. I can instantiate the array without issue but assigning it using info[0].as throws errors.

My c++ code is

#include <napi.h>

using namespace Napi;
using namespace std;

Value Add(const CallbackInfo& info) 
{
  Env env = info.Env();


  Array result = Napi::Array::New(env);
  Array a = info[0].As<Array>;

  double arg1 = info[1].As<Number>().DoubleValue();
  Number num = Napi::Number::New(env, 2 + arg1);

  return num;
}

The error I am getting is

../cppsrc/main.cpp: In function ‘Napi::Value Add(const Napi::CallbackInfo&)’:
../cppsrc/main.cpp:12:21: error: conversion from ‘<unresolved overloaded function type>’ to non-scalar type ‘Napi::Array’ requested
   Array a = info[0].As<Array>;
             ~~~~~~~~^~~~~~~~~

What is the correct way to pass an array to c++? Is it even possible?

like image 447
Root0x Avatar asked Jan 01 '23 19:01

Root0x


2 Answers

This works for me:

void runSetPropertyAsyncWorker(const CallbackInfo& info) 
{
    std::string path = info[0].As<Napi::String>();
    int property = info[1].As<Number>();
    int dataSize = info[2].As<Number>();
    Array b = info[3].As<Array>();
    for(int i = 0; i<b.Length(); i++)
    {
      Napi::Value v = b[i];
      if (v.IsNumber())
      {
        int value = (int)v.As<Napi::Number>();
        ...
        ...
      }
    }

    ...
    ...

    Function callback = info[4].As<Function>();
    AsyncWorker* asyncWorker = new SetPropertyAsyncWorker(callback, ...);
    asyncWorker->Queue();
}
like image 175
Morten Frederiksen Avatar answered Jan 08 '23 08:01

Morten Frederiksen


Use Napi::Object. Napi::Array is actually inherited from Napi::Object.

You could replace the code Array a = info[0].As<Array>; with Array a = info[0].ToObject();.

You can then access the data members via Value operator[] (uint32_t index) const

Source: https://nodejs.github.io/node-addon-api/class_napi_1_1_object.html

Edit: Bonus feature, if an argument that is not an object is passed, this will automatically trigger an Error: Object Expected.

like image 39
Luke Avatar answered Jan 08 '23 06:01

Luke