Skip to content

Instantly share code, notes, and snippets.

@janneh
Created January 15, 2017 11:41
Show Gist options
  • Save janneh/48ac72929f4f62d488db83c91e1ace9e to your computer and use it in GitHub Desktop.
Save janneh/48ac72929f4f62d488db83c91e1ace9e to your computer and use it in GitHub Desktop.
node-gyp go
{
"targets": [
{
"target_name": "calculator",
"sources": [
"calculator.cc"
],
"libraries": [
"../calculator.a"
],
},
],
}
go build -buildmode c-archive -o calculator.a calculator.go
node-gyp configure
node-gyp build
#include "calculator.h"
#include <node.h>
namespace calc {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
using v8::Number;
using v8::Exception;
void add(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
// Check the number of arguments passed.
if (args.Length() < 2) {
// Throw an Error that is passed back to JavaScript
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Wrong number of arguments")));
return;
}
// Check the argument types
if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Wrong arguments")));
return;
}
// Perform the operation
Local<Number> num = Number::New(isolate, Sum(args[0]->NumberValue(), args[1]->NumberValue()));
// Set the return value (using the passed in
// FunctionCallbackInfo<Value>&)
args.GetReturnValue().Set(num);
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "add", add);
}
NODE_MODULE(calculator, init)
}
// package name: calculator
package main
import "C"
//export Sum
func Sum(x, y float64) float64 {
return x + y
}
func main() {
}
const calculator = require('./build/Release/calculator')
console.log('4 + 5 =', calculator.add(4, 5))
// => 4 + 5 = 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment