我正在尝试使用 NDK 将 v8 嵌入到 Android 应用程序中。
我有一个看起来像这样的 JNI 模块(未显示 JNI 映射代码):
#include <jni.h>
#include <android/log.h>
#include <v8.h>
using namespace v8;
static jlong getMagicNumber() {
HandleScope handle_scope;
Persistent<Context> context = Context::New();
Context::Scope context_scope(context);
Handle<String> source = String::New("40 + 2");
Handle<Script> script = Script::Compile(source);
Handle<Value> result = script->Run();
context.Dispose();
return result->NumberValue();
}
我第一次跑步getMagicNumber
,它正确运行并返回 42。第二次我尝试运行它时,它崩溃了。
具体来说,这ASSERT
在 v8 中看到isolate.h
fails:
// Returns the isolate inside which the current thread is running.
INLINE(static Isolate* Current()) {
Isolate* isolate = reinterpret_cast<Isolate*>(
Thread::GetExistingThreadLocal(isolate_key_));
ASSERT(isolate != NULL);
return isolate;
}
听起来很像这个问题 https://groups.google.com/forum/?fromgroups=#!topic/v8-users/Px0JcsfDjYA,这建议使用v8::Locker
获得“对该隔离区的独家访问权”。
通过添加一个简单的Locker l;
到顶部getMagicNumber
,不再发生崩溃。当我不注意时,那些可以自行解决的问题很容易就会自行破坏。
我对为什么这能解决我的问题只有最微弱的理解,并且我收到了我正在使用的编译器警告v8::Locker
以一种已弃用的方式。推荐的方法是为其提供一个v8::Isolate
作为一个论据v8::Locker
的构造函数,但我不知道如何“获得”隔离。
最终:根据v8的当前状态,解决这个问题的正确方法是什么,以及why?