Skip to content

Commit

Permalink
See #1. Add example on native C++ bindings
Browse files Browse the repository at this point in the history
  • Loading branch information
Glavin001 committed Nov 12, 2014
1 parent 7f412fb commit 42b046e
Show file tree
Hide file tree
Showing 5 changed files with 97 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@

build

# Logs
logs
*.log
Expand Down
24 changes: 24 additions & 0 deletions cpp-bindings/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# C++ Modules in Node.js

## Installation

```bash
npm install -g node-gyp
```

## Usage

```bash
node-gyp configure build
```

```bash
node test.js
```

## Links
- https://www.npmjs.org/package/node-gyp
- http://nkzawa.tumblr.com/post/46089897239/how-to-write-native-node-addons
- http://www.slideshare.net/nsm.nikhil/writing-native-bindings-to-nodejs-in-c
- http://luismreis.github.io/node-bindings-guide/docs/returning.html

57 changes: 57 additions & 0 deletions cpp-bindings/addon.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// hello.cc
#include <node.h>
#include <v8.h>

using namespace v8;

/**
* function Hello() {
* var hello = 'hello ';
* var arg = arguments[0];
* return hello + arg;
* }
*/
Handle<Value> Hello(const Arguments& args) {
HandleScope scope;

Local<String> hello = String::New("hello ");
Local<String> arg = args[0]->ToString();
return scope.Close(String::Concat(hello, arg));
}

/**
* function Square() {
* var a = arguments[0]
* var sq = a * a;
* return sq;
* }
*/
Handle<Value> Square(const Arguments& args) {
HandleScope scope;

int a = args[0]->Int32Value();
int sq = a * a;

return scope.Close(Integer::New(sq));
}

/**
* function Init(exports) {
* var hello = Hello;
* exports.hello = hello;
* }
*/
void Init(Handle<Object> exports) {
Local<Function> hello = FunctionTemplate::New(Hello)->GetFunction();
exports->Set(String::NewSymbol("hello"), hello);

Local<Function> square = FunctionTemplate::New(Square)->GetFunction();
exports->Set(String::NewSymbol("square"), square);
}

/**
* NODE_MODULE is a macro defined at node.h
* first argument is module name (the file created at compile time)
*/
NODE_MODULE(addon, Init)

8 changes: 8 additions & 0 deletions cpp-bindings/binding.gyp
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
'targets': [
{
'target_name': 'addon',
'sources': [ 'addon.cc' ]
}
]
}
5 changes: 5 additions & 0 deletions cpp-bindings/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// hello.js
var addon = require('./build/Release/addon');
console.log(addon.hello('world')); // 'hello world'

console.log('Square 5: '+addon.square(5));

0 comments on commit 42b046e

Please sign in to comment.