How to save a link to a function so that I can return it later in the node.js C ++ add-ons module?

Here is the node.js add-on module written in C ++ and built using node -gyp. When StoreFunction I try to keep a pointer to a function, so I can use it later

When I try to call it later, but in InvokeFunction I get a segmentation error. What confused me, if I examined the pointer in both functions (using cout), they have the same meaning.

So, I assume either a change in the call to contextual changes between calls to two functions, or I don’t understand what I am pointing to.

All (ummmmmm) pointers gratefully received my problem here ..............

#include <node.h>
#include <v8.h>

using namespace v8;
v8::Persistent<v8::Function> callbackFunction;
 Handle<Value> StoreFunction(const Arguments& args) {
    HandleScope scope;
    callbackFunction = *Local<Function>::Cast(args[0]);
    return scope.Close(Undefined());
}

Handle<Value> InvokeFunction(const Arguments& args) {
    HandleScope scope;
    Local<Value> argv[1] = { String::New("Callback from InvokeFunction")};
    callbackFunction->Call(Context::GetCurrent()->Global(), 1, argv);
    return scope.Close(Undefined());
}

void init(Handle<Object> target) {
  NODE_SET_METHOD(target, "StoreFunction", StoreFunction);
  NODE_SET_METHOD(target, "InvokeFunction", InvokeFunction);
}

NODE_MODULE(someaddonmodule, init);

And of course, some js calls ...........

var myaddon = require('../build/Release/someaddonmodule');
myaddon.StoreFunction(function(data){   
    console.log("Called back: "+data);
});

myaddon.InvokeFunction();   //causes a segmentation fault
+4
1

, Java Toto. , . , V8, .

, V8, , :

Persistent< Function > percy;
Local<Function> callbackFunction = Local<Function>::Cast(args[0]);
percy = Persistent<Function>::New(callbackFunction);

-, V8, , , :)

+3

Source: https://habr.com/ru/post/1526082/


All Articles