我正在尝试创建一个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中出现“访问冲突读取位置”异常,就像Hzmy的quiestion一样。
嵌入铬的文档包含以下内容:
因此,在使用javascript模型进行操作之前,您应该打开正确的连接。如果V8当前不在上下文中,或者需要检索和存储对上下文的引用,则可以使用两个可用的CefV8Context静态方法之一。GetCurrentContext()返回当前正在执行JS的框架的上下文。GetEnteredContext()返回JS执行开始的框架的上下文。例如,如果frame1中的函数调用frame2中的函数,则当前上下文将为frame2,而输入的上下文将为frame1。
如果V8在上下文中,则只能创建,修改和执行数组,对象和函数,就函数而言,只能执行。如果V8不在上下文中,则应用程序需要通过调用Enter()进入上下文并通过调用Exit()退出上下文。仅应使用Enter()和Exit()方法:
在现有上下文之外创建V8对象,函数或数组时。例如,在创建JS对象以响应本机菜单回调时。
在当前上下文以外的上下文中创建V8对象,函数或数组时。例如,如果源自frame1的呼叫需要修改frame2的上下文。
这就是为什么我无法创建对象但能够创建js字符串的原因。您还可以看到一般用法示例。
下面的代码解决了这个问题:
if (callbackCtxt.get() && callbackCtxt->Enter())
{
CefRefPtr<CefV8Value> object = CefV8Value::CreateObject(NULL);
// call ExecuteFunctionWithContext and perform other actions
callbackCtxt->Exit();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句