Skip to content

Instantly share code, notes, and snippets.

@a7ul
Created June 13, 2018 10:38
Show Gist options
  • Save a7ul/bbe8fea1b42d8f889cd799f7cc1de5f6 to your computer and use it in GitHub Desktop.
Save a7ul/bbe8fea1b42d8f889cd799f7cc1de5f6 to your computer and use it in GitHub Desktop.
blog-on-node-addon-function-with-params
diff --git a/cppsrc/Samples/functionexample.cpp b/cppsrc/Samples/functionexample.cpp
index 0bd9bc2..37b7eb9 100644
--- a/cppsrc/Samples/functionexample.cpp
+++ b/cppsrc/Samples/functionexample.cpp
@@ -4,13 +4,33 @@ std::string functionexample::hello(){
return "Hello World";
}
+int functionexample::add(int a, int b){
+ return a + b;
+}
+
Napi::String functionexample::HelloWrapped(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
Napi::String returnValue = Napi::String::New(env, functionexample::hello());
return returnValue;
}
+
+Napi::Number functionexample::AddWrapped(const Napi::CallbackInfo& info) {
+ Napi::Env env = info.Env();
+ if (info.Length() < 2 || !info[0].IsNumber() || !info[1].IsNumber()) {
+ Napi::TypeError::New(env, "Number expected").ThrowAsJavaScriptException();
+ }
+
+ Napi::Number first = info[0].As<Napi::Number>();
+ Napi::Number second = info[1].As<Napi::Number>();
+
+ int returnValue = functionexample::add(first.Int32Value(), second.Int32Value());
+
+ return Napi::Number::New(env, returnValue);
+}
+
Napi::Object functionexample::Init(Napi::Env env, Napi::Object exports) {
exports.Set("hello", Napi::Function::New(env, functionexample::HelloWrapped));
+ exports.Set("add", Napi::Function::New(env, functionexample::AddWrapped));
return exports;
}
diff --git a/cppsrc/Samples/functionexample.h b/cppsrc/Samples/functionexample.h
index 44563aa..e15aa7b 100644
--- a/cppsrc/Samples/functionexample.h
+++ b/cppsrc/Samples/functionexample.h
@@ -4,6 +4,10 @@ namespace functionexample {
std::string hello();
Napi::String HelloWrapped(const Napi::CallbackInfo& info);
- Napi::Object Init(Napi::Env env, Napi::Object exports);
+ int add(int a, int b);
+ Napi::Number AddWrapped(const Napi::CallbackInfo& info);
+
+ Napi::Object Init(Napi::Env env, Napi::Object exports);
+
}
diff --git a/index.js b/index.js
index e91b98f..72860f8 100644
--- a/index.js
+++ b/index.js
@@ -1,4 +1,5 @@
const testAddon = require('./build/Release/testaddon.node');
console.log('addon',testAddon);
-console.log(testAddon.hello());
+console.log('hello ', testAddon.hello());
+console.log('add ', testAddon.add(5, 10));
module.exports = testAddon;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment