使用某些C文件创建动态库。此动态库由C ++函数使用。其中一个C函数调用C ++函数。而这又将调用Javascript函数回调。我在C ++函数中遇到了分段错误。
这是代码, 在test.h中,
#ifdef __cplusplus
extern "C" {
#endif
void cppFunc(void);
#ifdef __cplusplus
}
#endif
这是test.c中的代码
#include "test.h"
void cFunc(void){
/* some code */
cppFunc();
}
这是test.cpp中的代码
#include "test.h"
static Nan::Persistent<v8::Function> callback;
void storeFunc(const v8::FunctionCallbackInfo<v8::Value>& args){
if(args[0]->IsFunction()){
Local<Function> cb = Local<Function>::Cast(args[0]);
callback.Reset(cb);
}
}
void cppFunc(void){
Isolate *isolate = Isolate::GetCurrent();
Local<Function> c_back = Local<Function>::New(isolate, callback);
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), c_back, 0, {});
}
void init(Handle<Object> exports, Handle<Object> module)
{
NODE_SET_METHOD(exports, "FuncStore", storeFunc);
}
NODE_MODULE(test, init)
test.node是使用“node-gyp configure build”命令创建的。没有显示错误或警告。
以下是我的test.js文件,
var sample = require("./build/Release/test.node");
sample.FuncStore(function(){
console.log("Callback has been called!!");
});
在“node test.js”执行test.js时,当cFunc()调用cppFunc()时会发生分段错误。分段错误恰好发生在“Local c_back = Local :: New(isolate,callback)”行中。在cppFunc()中。
可能是什么原因?
答案 0 :(得分:0)
一种可能性是指针“isolate”是NULL
。访问没有值或无效值的指针可能会导致分段错误。你应该通过执行以下方式检查它是否存在:
Isolate *isolate = Isolate::GetCurrent();
if (isolate) {
//it is now safe to use isolate
Local<Function> c_back = Local<Function>::New(isolate, callback);
Nan::MakeCallback(Nan::GetCurrentContext()->Global(), c_back, 0, {});
}
else {
//possibly generate your own warning here
}
作为旁注,似乎不推荐使用Isolate :: GetCurrent https://github.com/nodejs/node/commit/409d413363