Is there a way to call JS functions from C++ through node.js (as callbacks or something like that)? If yes, how? I\'m searching for it on the web, but haven\'t found any hel
Of course you can. For example, if you want to write a simple factorial function in C++, you could do something like
#include
using namespace v8;
int factorial(int n) {
if (n == 0) return 1;
else return n * factorial(n - 1);
}
void Factorial(const FunctionCallbackInfo& args) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope(isolate);
if (args.Length() != 2) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong number of arguments")));
} else {
if (!(args[0]->IsNumber() && args[1]->IsFunction())) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong arguments type")));
} else {
int result = factorial(args[0]->Int32Value());
Local callbackFunction = Local::Cast(args[1]);
const unsigned argc = 1;
Local argv[argc] = { Number::New(isolate, result) };
callbackFunction->Call(isolate->GetCurrentContext()->Global(), argc, argv);
}
}
}
void Init(Handle
And in your JavaScript file, call it like this
var factorialAddon = require('./addons/Factorial');
factorialAddon.factorial(5, function (result) {
console.log(result);
});