Calling JavaScript from C++ with node.js

后端 未结 3 1655
一生所求
一生所求 2020-12-29 05:01

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

3条回答
  •  忘掉有多难
    2020-12-29 05:32

    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 exports) {
        NODE_SET_METHOD(exports, "factorial", Factorial);
    }
    
    NODE_MODULE(Factorial, Init)
    
    
    

    And in your JavaScript file, call it like this

    var factorialAddon = require('./addons/Factorial');
    factorialAddon.factorial(5, function (result) {
        console.log(result);
    });
    

    提交回复
    热议问题