具有持久功能的JavaScript中的分割故障

Segmentation fault in javascript with persistent function

本文关键字:JavaScript 分割 故障 功能      更新时间:2023-10-16

动态库是使用某些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(孤立,回调)"的行中。在cppfunc()中。

原因是什么?

一种可能性是指针"隔离"是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
}

作为附带说明,似乎是孤立:: getCurrent被弃用https://github.com/nodejs/nodejs/node/commit/409d413363