我有一个为节点0.10开发的node.js插件,我需要为当前节点更新它。我修复了大部分api更改,但我仍然坚持存储一个静态回调指针以便以后调用的问题。我修改了3_callback示例插件来显示我到目前为止所做的以及我在编译期间得到的错误。这是我到目前为止(编译错误添加为注释行):
#include <node.h>
using namespace v8;
typedef Persistent<Function> CallBack_t;
static CallBack_t MyCallBack;
void CallBack( char* str ) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope( isolate );
const unsigned argc = 1;
Local<Value> argv[ argc ] = { String::NewFromUtf8( isolate, str ) };
Local<Function> cb = Local<Function>::New( isolate, MyCallBack );
cb->Call( isolate->GetCurrentContext()->Global(), argc, argv );
}
void RunCallback( const FunctionCallbackInfo<Value>& args ) {
Isolate* isolate = Isolate::GetCurrent();
HandleScope scope( isolate );
Local<Function> cb = Local<Function>::Cast( args[ 0 ] );
MyCallBack = CallBack_t::New( isolate, cb );
//..\addon.cc( 24 ) : error C2664 : 'v8::Function *v8::PersistentBase<T>::New(v8::Isolate *,T *)' : cannot convert argument 2 from 'v8::Local<v8::Function>' to 'v8::Function *' [E:\SoftwareProjects\node-addon-examples\trunk\3_global_callback\node_0.12\build\addon.vcxproj]
// with
// [
// T = v8::Function
// ]
//..\addon.cc( 24 ) : note : No user - defined - conversion operator available that can perform this conversion, or the operator cannot be called CallBack( "JavaScriptCallBack calling" );
}
void Init( Handle<Object> exports, Handle<Object> module ) {
NODE_SET_METHOD( module, "exports", RunCallback );
}
NODE_MODULE( addon, Init )
我尝试了不同的选择,但到目前为止都没有。错误在哪里?
答案 0 :(得分:1)
解决代码中的错误:
cannot convert argument 2 from 'v8::Local<v8::Function>' to 'v8::Function *'
这应该解决它:
v8::Local<v8::Function> cb = std::Local<v8::Function>::Cast(args[0]);
v8::Function * f_ptr = *cb;
。
在Node V8版本4.X.X中静态存储和调用JS-Callback函数:
callbacks.cxx:
v8::Persistent<v8::Function> r_call;
/** Save the JS-Callback for later use.
* If args[0] is not a function (such as null), remove callback
*/
void RunCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
if (args[0]->IsFunction()) {
v8::Local<v8::Function> func = v8::Local<v8::Function>::Cast(args[0]);
v8::Function * ptr = *func;
r_call.Reset(isolate, func);
}
else {
r_call.Reset();
}
}
/* Run the saved callback if there is one. */
void run() {
if(!r_call.IsEmpty()) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::Local<v8::Function> func = v8::Local<v8::Function>::New(isolate, r_call);
if (!func.IsEmpty()) {
const unsigned argc = 1;
v8::Local<v8::Value> argv[argc] =
{ v8::String::NewFromUtf8(isolate, "hello world") };
func->Call(v8::Null(isolate), argc, argv);
}
}
}
test.js:
const mod = require("...");
mod.RunCallback((msg) => { console.log(msg); });
mod.run();
- 使用以下命令测试:node-gyp v4.4.4,MSVS2013,SWIGv3.0.10 -