Node.JS,C ++模块:当我尝试调用Local <Array>的Length方法时为什么会出现段错误?

当我从js代码和func()调用func()调用arr->Length()然后我有段错误。

但有时候,我在stdout有奇怪的随机值: 283132217, -1222622919, -42974919, -112180935, 997212473, -1412415175.

这是一个例子:

 #include <node.h> using namespace v8; Local<Array> arr = Array::New(); Handle<Value> func(const Arguments &args) { HandleScope scope; printf("%d\n", arr->Length()); return scope.Close(Undefined()); } void init(Handle<Object> target) { target->Set( String::NewSymbol("func"), FunctionTemplate::New(func)->GetFunction() ); } NODE_MODULE(ctest, init); 

我不是V8的专家,但我可以解决这样的问题:

 Persistent<Array> arr = Persistent<Array>::New(Array::New()); Handle<Value> func(const Arguments &args) { HandleScope scope; printf("%d\n", arr->Length()); return scope.Close(Undefined()); } 

或者把本地句柄放到你的函数中:

 Handle<Value> func(const Arguments &args) { HandleScope scope; Local<Array> arr = Array::New(); printf("%d\n", arr->Length()); return scope.Close(Undefined()); }