javascript - V8 console.log 不打印
问题描述
我正在尝试将 v8 嵌入到我的应用程序中,我对查看 V8 环境中包含的内容感到很困惑(duktape 不包含控制台实现),并且似乎 v8 确实包含了一个实现,但是当我调用console.log
它时不会打印任何内容,相反,它只是打印 undefined (我假设它是 的返回值console.log
) 那么如何将默认std::cout
输出与console.log
.
这是我目前的代码,我正在使用默认的 hello world 代码进行了轻微修改。
int main(int argc, char* argv[]) {
// Initialize V8.
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();
// 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::Isolate::Scope isolate_scope(isolate);
// Create a stack-allocated handle scope.
v8::HandleScope handle_scope(isolate);
// Create a new context.
v8::Local<v8::Context> context = v8::Context::New(isolate);
// Enter the context for compiling and running the hello world script.
v8::Context::Scope context_scope(context);
{
// Create a string containing the JavaScript source code.
v8::Local<v8::String> source =
v8::String::NewFromUtf8(isolate, R"(
console.log("does not print?")
)",
v8::NewStringType::kNormal)
.ToLocalChecked();
// Compile the source code.
v8::Local<v8::Script> script =
v8::Script::Compile(context, source).ToLocalChecked();
// Run the script to get the result.
v8::Local<v8::Value> result = script->Run(context).ToLocalChecked();
// Convert the result to an UTF8 string and print it.
v8::String::Utf8Value utf8(isolate, result);
printf("%s\n", *utf8);
}
}
// Dispose the isolate and tear down V8.
isolate->Dispose();
v8::V8::Dispose();
v8::V8::ShutdownPlatform();
delete create_params.array_buffer_allocator;
std::cin.get();
return 0;
}
解决方案
尝试以下操作:
#include "src/debug/interface-types.h"
- 定义您自己的“控制台委托”类,派生自
debug::ConsoleDelegate
- 覆盖您感兴趣的任何方法,例如
void Log(const debug::ConsoleCallArguments& args, const v8::debug::ConsoleContext&) override;
- 实例化它并
debug::SetConsoleDelegate(isolate, &your_console_delegate);
在创建你的之后调用Isolate
要查看示例,请从https://cs.chromium.org/chromium/src/v8/src/d8/d8-console.h?l=14&gsn=D8Console开始并跟踪它的使用位置。
推荐阅读
- php - Laravel Eloquent GroupBy 多对一关系
- kubernetes - 在 Kubernetes 中创建具有单独 pod 的 Replicaset
- react-native - 弹出水平动画
- reactjs - 反应组件元素/数据不呈现但登录控制台
- reactjs - 如何在不弹出 cra 的情况下捕获反应错误,例如使用 className 而不是循环丢失的类或键
- rust - 如何在没有 for 循环的情况下在元组 Vec 中转换两个嵌套的 HashMap?
- sql - 在 JSONB 中查询对象数组
- c++ - X DevAPI mysqlx::Session() over linux socket 失败并显示“CDK 错误:意外消息”
- laravel - 当我们输入输入元素时的 Livewire 触发方法
- python - 尽管我在 settings.py 文件中提供了 CORS_ORIGIN_ALLOW_ALL = True