Friday 21 April 2017

node.js addon call javascript function failed

I want to call a javascript function(which is in the test.js) from my C++ addon by name but not pass it as an argument in the FunctionCallbackInfo<Value> object. Version of my node.js is 6.10.2.

test.js:

function callme(msg)
{
    console.log(msg);
}
const addon = require('./build/Debug/addon11');
addon.StartRun();

addon.cc:

#include<node.h>

namespace demo
{
    using v8::FunctionCallbackInfo;
    using v8::Isolate;
    using v8::Local;
    using v8::Object;
    using v8::String;
    using v8::Value;
    using v8::Exception;
    using v8::Function;
    using v8::Context;
    using v8::HandleScope;
    using v8::MaybeLocal;

    void Method(const FunctionCallbackInfo<Value>& args)
    {
        Isolate* isolate = Isolate::GetCurrent();
        HandleScope scope(isolate);
        Local<Context> context = isolate->GetCurrentContext();
        Local<Object> global = context->Global();
        if (global.IsEmpty() || global->IsNull())
        {
            return;
        }
        MaybeLocal<Value> mbValue = global->Get(String::NewFromUtf8(isolate, "callme"));
        if (mbValue.IsEmpty())
        {
            isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate, "can't find the function callme!")));
            return;
        }
        Local<Value> vTmp = mbValue.ToLocalChecked();
        if (!vTmp->IsFunction())
        {
            return;//it will retun here
        }
        Local<Function> callFunc = Local<Function>::Cast(vTmp);
        Local<Value> argv[] = { String::NewFromUtf8(isolate, "call from c++") };
        callFunc->Call(Null(isolate), 1, argv);
    }

    void init(Local<Object> exports)
    {
        NODE_SET_METHOD(exports, "StartRun", Method);
    }

    NODE_MODULE(addon11, init)
}

when I debug the code it returns here:

        Local<Value> vTmp = mbValue.ToLocalChecked();
        if (!vTmp->IsFunction())
        {
            return;//it will retun here
        }



via zhonghemin

No comments:

Post a Comment