關於Delphi接口不能強制轉化的補充說明

其實Delphi爲了速度的原因,對於接口是採用直接解析接口在實例中的偏移來得到的.這個可以從下面的代碼中看到:

var
mInt: ITestInterface;
mInt2: ITestInterface2;
begin
mInt :
= TTestInterface2.Create;
mInt2 :
= TTestInterface2.Create;
end;


其中 mInt := TTestInterface2.Create 代碼爲:
mov dl, $01
mov eax, [$00452e4]
call TObject.Create
mov edx, eax
jz 
+$03
sub edx, 
-$0C
lea eax, [ebp
-$04]
call @IntfCopy

而 mInt2 := TTestInterface2.Create 代碼爲:
mov dl, $01
mov eax, [$00452e4]
call TObject.Create
mov edx, eax
jz 
+$03
sub edx, 
-$0C
lea eax, [ebp
-$08]
call @IntfCopy


但 對於接口之間的轉化時, CSDN的halfdream(哈欠) 兄說的很對, Delphi在call @IntfCast裏調用了@QueryInterface, 而這裏面的代碼, 其實是在System的TObject對象的GetInterface這個方法中, 但這個方法有個問題, 它需要GUID, 但我們實際可以在Delphi中使用無GUID的接口, 那麼就會發現, 根本無法進行轉化

比如:
INoGUIDInterface = interface
procedure NoGUID;
end;

INoGUIDInterface2 
= interface
procedure NoGUID2;
end;

var
mInt: INoGUIDInterface;
mInt2: INoGUIDInterface2;
begin
mInt :
= TTestNoGUIDInterface2.Create;
mInt.NoGUID;

mInt2 :
= mInt as INoGUIDInterface2;
mInt2.NoGUID2;
end;


編譯就會出錯了, Operator not applicable to this operand type 根本就不支持. 所以表明接口時還是隨手加上GUID的比較好 
發佈了48 篇原創文章 · 獲贊 0 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章