Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add template functions to bind easily #639

Closed
chokobole opened this issue Dec 23, 2019 · 2 comments
Closed

Add template functions to bind easily #639

chokobole opened this issue Dec 23, 2019 · 2 comments

Comments

@chokobole
Copy link

When we bind a function, we have to write argument checking and type conversion every time per each function. The example below is one of them.

#include "napi.h"

double CAdd(double arg0, double arg1) { return arg0 + arg1; }

Napi::Value Add(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();
  if (info.Length() < 2) {
    Napi::TypeError::New(env, "Wrong number of arguments").ThrowAsJavaScriptException();
    return env.Null();
  }
  if (!info[0].IsNumber() || !info[1].IsNumber()) {
    Napi::TypeError::New(env, "Wrong arguments").ThrowAsJavaScriptException();
    return env.Null();
  }
  double arg0 = info[0].As<Napi::Number>().DoubleValue();
  double arg1 = info[1].As<Napi::Number>().DoubleValue();
  Napi::Number num = Napi::Number::New(env, CAdd(arg0, arg1);
  return num;
}

And I made some template functions not to write everytime like below.

#include "node_binding/typed_call.h"

double CAdd(double arg0, double arg1) { return arg0 + arg1; }

Napi::Value Add(const Napi::CallbackInfo& info) {
  return node_binding::TypedCall(info, &CAdd);
}

These codes are here and if you think it is good, I want to PR! :)

@gabrielschulhof
Copy link
Contributor

@chokobole Thank you for working on this feature! We spoke about this in the past two N-API team meetings and we believe that the best course of action would be to release this as a package on npm so that we might later consider it for integration into node-addon-api. The reason we wish to take this approach is that node-addon-api's core mission is to expose the plain C N-API as C++ wrappers. This feature adds functionality on top of that core mission, and so might live as an independent package with a dependency on node-addon-api.

@legendecas
Copy link
Member

Maybe effects can be made to help modules like this to incubate and expose to more audiences.

  1. NPM integration of N-API headers like what node-addon-api do in https://github.com/nodejs/node-addon-api/blob/master/index.js;
  2. links from node-addon-api documents;
  3. NPM/GitHub tags.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants