我正在尝试使用 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
失败:
// 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;
}
这听起来很像这个问题,它建议使用v8::Locker
来获得“对隔离的独占访问权”。
Locker l;
通过在 的顶部添加一个简单的getMagicNumber
,不再发生崩溃。当我不注意时,容易解决的问题往往会自行解决。
我对为什么这能解决我的问题只有最微不足道的理解,而且我收到了编译器警告,我正在v8::Locker
以不推荐的方式使用它们。推荐的方法是为它提供 av8::Isolate
作为v8::Locker
构造函数的参数,但我不知道我应该如何“获得”一个隔离。
最终:根据 v8 的当前状态,解决此问题的正确方法是什么,为什么?