WebAssembly.instantiate既未调用,也未捕获到嵌入式v8

时间:2019-06-03 14:03:51

标签: javascript c++ v8 webassembly embedded-v8

我尝试在v8 7.2中为我的Android项目提供WebAssembly功能。我已成功导入v8作为静态库。但是我遇到了一个问题,即WebAssembly既没有调用then也没有调用catch回调。 这是我的代码如下:

std::unique_ptr<v8::Platform> platform;
v8::Isolate *isolate;
v8::Persistent<v8::Context> persistentContext;
void runMain();
void runScript();
void _log(const v8::FunctionCallbackInfo<v8::Value>& info) {
  v8::String::Utf8Value utf(isolate, info[0].As<v8::String>());
  __android_log_print(ANDROID_LOG_DEBUG, "V8Native", "%s",*utf);
}

void JNICALL
Java_com_hustunique_v8demoapplication_MainActivity_initV8(JNIEnv *env, jobject /* this */) {
  // Initialize V8.
  v8::V8::InitializeICU();
  platform = v8::platform::NewDefaultPlatform();
  v8::V8::InitializePlatform(&(*platform.get()));
  v8::V8::Initialize();
  runMain();
}

void runMain() {
  // Create a new Isolate and make it the current one.

  v8::Isolate::CreateParams create_params;
  create_params.array_buffer_allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator();
  isolate = v8::Isolate::New(create_params);
//  isolate->Enter();
  v8::Isolate::Scope isolate_scope(isolate);
  v8::HandleScope scope(isolate);


  auto global_template = v8::ObjectTemplate::New(isolate);
  global_template->Set(v8::String::NewFromUtf8(isolate, "log"), v8::FunctionTemplate::New(isolate, _log));   // set log function here, as it is used in my sample javascript code
  // Enter the context for compiling and running the sample script.
  v8::Local<v8::Context> context = v8::Context::New(isolate, nullptr, global_template);
  persistentContext.Reset(isolate, context);

  // Run the script to get the result.
  runScript();

}

void runScript() {
  // sample wasm javascript code here.
  const char *csource = R"(
    WebAssembly.instantiate(new Uint8Array([0,97,115,109,1,0,0,0,1,8,2,96,1,127,0,96,0,0,2,8,1,2,106,
      115,1,95,0,0,3,2,1,1,8,1,1,10,9,1,7,0,65,185,10,16,0,11]),
      {js:{_:console.log('Called from WebAssembly Hello world')}}).then(function(obj) {
        log('Called with instance ' + obj);
      }).catch(function(err) {
        log('Called with error ' + err);
      });
  )"; // should call my Hello World log and trigger the error or return the instance successfully

  v8::HandleScope handle_scope(isolate);
  auto ctx = persistentContext.Get(isolate);
  v8::Context::Scope context_scope(ctx);
  v8::TryCatch try_catch(isolate);
  v8::Local<v8::String> source = v8::String::NewFromUtf8(isolate, csource,
                                                         v8::NewStringType::kNormal).ToLocalChecked();

  v8::Local<v8::Script> script =
      v8::Script::Compile(ctx, source).ToLocalChecked();
  v8::Local<v8::Value> result;
  if (!script->Run(ctx).ToLocal(&result)) {
    ReportException(isolate, &try_catch); // report exception, ignore the implementation here
    return;
  }
  // Convert the result to an UTF8 string and print it.
  v8::String::Utf8Value utf8(isolate, result);
  __android_log_print(ANDROID_LOG_INFO, "V8Native", "%s\n", *utf8);

}

在上面的演示中,我获得了Called from WebAssembly Hello world作为例外的输出,但是我无法获得错误消息或实例信息。

与上面的演示相比,我在website上做了一个简单的例子,这是网站上的输出,我认为可以很容易地复制出来:

Called from WebAssembly Hello world
Called with error LinkError: WebAssembly.instantiate(): Import #0 module="js" function="_" error: function import requires a callable

在我的演示中,似乎没有从WebAssembly返回的承诺中调用resolvereject。在检查v8::Local<v8::Value> result方法中的runScript类型之后,v8运行时确认它是一个Promise对象。

我在这里尝试了几件事,但没有一个起作用:

  1. 致电v8 :: Isolate :: RunMicroTasks()。什么都没发生
  2. result方法末尾将v8::Local<v8::Promise>投射到runScript,然后运行:
auto resolver = v8::Resolver::New(context)->toLocalChecked();
while (promise->State() == v8::PromiseState::kPending) {
    isolate->RunMicroTasks();
}
if (promise->State() == v8::PromiseState::kFullfilled) {
    resolver->Resolve(context, promise->Result());
}
if (promise->State() == v8::PromiseState::kRejected) {
    resolver->Reject(context, promise->Result());
}

此代码段也不起作用,此外,它停留在kPending状态。

我搜索了flush the promise queue之类的东西,但没有任何解决方法。我在这里想念什么?

1 个答案:

答案 0 :(得分:3)

WebAssembly的异步编译API在v8 :: Platform的后台线程之一上注册正在进行的工作,最终,将来,将有一个任务发布到前台线程,以解决对编译的承诺。

要实现此承诺,您需要启动消息循环并运行所有待处理的微任务:

v8::platform::PumpMessageLoop(platform.get(), isolate);
isolate->RunMicrotasks();

根据完成编译所需的时间,可能需要执行更长的抽空时间。