WebBrowser 释放注意事项(Delphi)
---这篇文章之前写的时候没有进行深入地分析,现在被认为是狭义的(因为EmwbBrowser的BUG,错怪RTL了。)。请参看后续文章---
Code
由于WebBrowser是基于COM技术的ActiveX控件,而Delphi对COM的支持又不尽人意,因此在使用TWebBrowser以及其派生对象都要有这样或那样的异常,错误提示大概都是:“你没有按照上帝的旨意去使用WebBrowser ”。今天我就遇到了在WebBrowser释放时候发生的的奇怪异常。
代码如下:
1
var
2
Document:IHTMLDocument2;
3
Url:WideString;
4
begin
5
Document=Browser.Document as IHTMLDocument2;
6
Url:=Document.url;
7
ShowMessage(Url);
8
Browser.Free;
9
end;
10
var2
Document:IHTMLDocument2;3
Url:WideString;4
begin5
Document=Browser.Document as IHTMLDocument2;6
Url:=Document.url;7
ShowMessage(Url);8
Browser.Free;9
end;10

以上代码执行后将会报AV错误,跟踪了一下RTL代码,发现错误出在:
而且这段代码是在End语句之后,是底层RTL释放IInterFace接口产生的。由于WebBrowser已经调用了Free方法,因此Document所指向的IHTMLDocument2已经被释放。RTL在每个函数执行完毕后例行释放该函数的局部变量,遇到了Document便释放之。于是AV异常爆发了。
你可能会想把Document:=nil;来避免这次不按上帝旨意的操作。不过不幸的告诉你,这是不行的。错误代码如下:
1
var
2
Document:IHTMLDocument2;
3
Url:WideString;
4
begin
5
Document=Browser.Document as IHTMLDocument2;
6
Url:=Document.url;
7
ShowMessage(Url);
8
Document:=nil;
9
Browser.Free;
10
end;
11
var2
Document:IHTMLDocument2;3
Url:WideString;4
begin5
Document=Browser.Document as IHTMLDocument2;6
Url:=Document.url;7
ShowMessage(Url);8
Document:=nil;9
Browser.Free;10
end;11

要解决这个错误,目前我只找到了一个方法,那就是不声明局部变量,直接As转型,代码是这样的:
1
var
2
Url:WideString;
3
begin
4
Url:=(Browser.Document as IHTMLDocument2).url;
5
ShowMessage(Url);
6
Browser.Free;
7
end;
8
var 2
Url:WideString;3
begin4
Url:=(Browser.Document as IHTMLDocument2).url;5
ShowMessage(Url);6
Browser.Free;7
end;8

这样虽然可以解决AV错误,但会令代码变得极为糟糕。

浙公网安备 33010602011771号