【发布时间】:2018-12-30 23:20:12
【问题描述】:
我开始嵌入 v8,但遇到了一些“意外行为”。当变量 value_ 最后不是 Reset 时,以下代码生成 Segmentation fault (core dumped)(请参阅代码中的注释)。但是,这不适用于上下文context_。为什么? This answer 似乎是相关的,但没有提供解释。
我的期望是isolate->Dispose() 兼顾两者。
#include <stdlib.h>
#include "include/libplatform/libplatform.h"
#include "include/v8.h"
int main(int argc, char* argv[]) {
v8::V8::InitializeICUDefaultLocation(argv[0]);
v8::V8::InitializeExternalStartupData(argv[0]);
std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
v8::V8::InitializePlatform(platform.get());
v8::V8::Initialize();
{
// Initialize V8.
// Create a new Isolate and make it the current one.
v8::Isolate::CreateParams create_params;
create_params.array_buffer_allocator =
v8::ArrayBuffer::Allocator::NewDefaultAllocator();
v8::Isolate* isolate = v8::Isolate::New(create_params);
v8::Global<v8::Context> context_;
v8::Global<v8::String> value_;
{
// Global Context Setup
v8::Isolate::Scope isolate_scope(isolate);
v8::HandleScope handle_scope(isolate);
v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);
v8::Local<v8::Context> context = v8::Context::New(isolate, NULL, global);
context_.Reset(isolate, context);
// Global Value Setup
v8::Context::Scope context_scope(context);
v8::Local<v8::String> value = v8::String::NewFromUtf8(isolate, "segfault", v8::NewStringType::kNormal).ToLocalChecked();
value_.Reset(isolate, value);
}
// value_.Reset(); // <- Why is this line needed?
// context_.Reset(); // <- Why is this line NOT needed?
isolate->Dispose();
delete create_params.array_buffer_allocator;
}
v8::V8::Dispose();
v8::V8::ShutdownPlatform();
return 0;
}
构建设置:
按照官方Getting started with embedding V8的运行示例中的说明进行操作。将代码保存到 sample/wasm.cc 并执行以下命令:
$ g++ -I. -O2 -Iinclude samples/segfault.cc -o segfault -lv8_monolith -Lout.gn/x64.release.sample/obj/ -pthread -std=c++17
$ ./segfault
【问题讨论】:
标签: c++ v8 embedded-v8