C++在自定义线程中创建cef对象

标签 c++ multithreading chromium-embedded

我正在尝试创建一个 javascript 对象以将其传递给函数回调,如下所示:

void MyClass::ThreadTaskOnSuccess(CefRefPtr<CefV8Value> callback, CefRefPtr<CefV8Context> callbackCtxt)
{
    if (!CefCurrentlyOn(TID_UI))
    {
        // switch to UI thread
        CefPostTask(TID_UI, NewCefRunnableMethod(this, &NewDownloadObject::CreateTempDownloadOnSuccess, callback, callbackCtxt));
        return;
    }
    // String creation works perfect!
    // CefRefPtr<CefV8Value> executionResult = CefV8Value::CreateString("test");

    // "Access violation" will be thrown
    CefRefPtr<CefV8Value> executionResult = CefV8Value::CreateObject(NULL);

    executionResult->SetValue("size", CefV8Value::CreateInt(123), V8_PROPERTY_ATTRIBUTE_NONE);
    executionResult->SetValue("fileName", CefV8Value::CreateString("some name of file"), V8_PROPERTY_ATTRIBUTE_NONE);

    CefV8ValueList args;
    args.push_back(executionResult);
    CefRefPtr<CefV8Value> retval;
    CefRefPtr<CefV8Exception> exception;
    if (callback->ExecuteFunctionWithContext(callbackCtxt, callbackCtxt->GetGlobal(), args, retval, exception, false))
    {
        if (exception.get())
        {
            throw CFdmException(exception->GetMessage().c_str());
        }
        else
        {
            // Execution succeeded.
        }
    }
}

但 CefV8Value::CreateObject(NULL) 总是返回空结果。我猜这是因为代码在自定义线程运行,因为某些任务必须在特殊线程中执行。

我说的对吗?以及如何切换到 cef 线程以与 V8 引擎一起工作并与之同步?

我错了吗?为什么 V8 会创建一个空对象?

已更新

我添加了 UI 线程切换。在那之后,我总是在 cef_v8value_create_object 中出现“访问违规读取位置”异常,就像在 the Hzmy's quiestion 中一样。 .

最佳答案

简而言之:您必须只能从有效线程访问 V8。

您可能错过了 How to use V8 JavaScript integration in client applications维基页面。

With CEF3 WebKit and JS execution run in a separate renderer process. The main thread in a renderer process is identified as TID_RENDERER and all V8 execution must take place on this thread. JS APIs that communicate between the browser and renderer processes should be designed using asynchronous callbacks. See http://www.chromium.org/developers/design-documents/extensions/how-the-extension-system-works/api-pattern-design-doc for an example.

关于C++在自定义线程中创建cef对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19088594/

相关文章:

c++ - 带有 clang 的 MacOSX 中的函数模板特化

c++ - C++ "concept"和鸭子类型(duck typing)之间有什么关系?

javascript - 覆盖 javascript 全局变量的可靠方法

javascript - 将网页呈现为 H.264

c++ - Windows 7 计时功能 - 如何正确使用 GetSystemTime Adjustment?

c++ - BOOST_FUSION_ADAPT_ADT找不到设置方法

java - Drawable不会在SurfaceView上绘制,Thread实现,不重写onDraw

java - 如何学习线程,尤其是在 Java 中

python - 工作线程内的 Queue.put 失败

java - 如何在 jcef 中正确使用 --enable-media-stream 开关