我在我的应用程序中使用Delphi嵌入Chromium(CEF1)并且无法读取URL的cookie数据。
我找到了this code(包含在下面),但在XE3上,当我在这一行上使用它时会遇到异常:
if WaitForSingleObject(vis.pEvent.Handle, INFINITE) = WAIT_OBJECT_0 then begin
例外是
项目guiclient.exe引发异常类EAccessViolation 消息'地址00000000处的访问冲突'。读取地址 00000000
暗示其中一个对象未正确创建或初始化。
我正在使用的代码(从上面的论坛链接复制)是:
TCustomVisitor = class (TCefCookieVisitorOwn)
private
fcookie: PCefCookie;
function visit(const name, value, domain, path: ustring; secure, httponly,
hasExpires: Boolean; const creation, lastAccess, expires: TDateTime;
count, total: Integer; out deleteCookie: Boolean): Boolean; override;
public
pEvent: TEvent;
function getCookies: PCefCookie;
constructor Create; override;
end;
constructor TCustomVisitor.Create;
begin
inherited;
pEvent := TEvent.Create(nil, False, False, 'ev.chromium');
new(fcookie);
end;
function TCustomVisitor.getCookies;
begin
Result := fcookie;
end;
function TCustomVisitor.visit(const name, value, domain, path: ustring; secure, httponly,
hasExpires: Boolean; const creation, lastAccess, expires: TDateTime;
count, total: Integer; out deleteCookie: Boolean): Boolean;
begin
fcookie.name := CefString(name);
fcookie.value := CefString(value);
fcookie.domain := CefString(domain);
fcookie.path := CefString(path);
fcookie.secure := secure;
fcookie.httponly := httponly;
fcookie.has_expires := hasExpires;
//fcookie.creation := DateTimeToCefTime(creation);
//fcookie.last_access := DateTimeToCefTime(lastAccess);
//fcookie.expires := DateTimeToCefTime(expires);
SetEvent(pEvent.Handle);
end;
procedure TfrmAuth.bt_okClick(Sender: TObject);
var
vis: TCustomVisitor;
cname, cvalue: uString;
ccookie: PCefCookie;
begin
if crm.Browser<>nil then begin
vis := TCustomVisitor.Create;
try
CefVisitUrlCookies(ed_url.Text, true, vis);
// !!! This line causes the access violation
if WaitForSingleObject(vis.pEvent.Handle, INFINITE) = WAIT_OBJECT_0 then begin
ccookie := vis.getCookies;
cname := CefString(@ccookie.name);
cvalue := CefString(@ccookie.value);
end;
finally
vis.Free;
end;
end;
end;
答案 0 :(得分:1)
这很简单。 CefVisitUrlCookies将对象作为引用计数接口,并在返回时释放它,并且obejct会自行销毁,因此在尝试访问Fried对象时会出现访问冲突。 要避免此问题,您可能希望在局部变量中存储对象的引用,或者显式调用_addref:
vis._AddRef();
CefVisitUrlCookies(ed_url.Text, true, vis);
WaitForSingleObject(...)
vis._Release();
或
ivis: ICefCookieVisitor;
...
ivis := vis;
CefVisitUrlCookies(ed_url.Text, true, ivis);
WaitForSingleObject(...)
ivis := nil;
并且不要忘记删除免费通话。您永远不应该使用引用计数显式释放接口对象。