通過TObject.GetInterface可以獲得對象的實例實現某個接口,前提條件是必須實例化對象后才能運行GetInterface
下面的方法可獲取類是否實現了某個接口,並返回接口的偏移:
function FindInterface(AClass: TClass; GUID:TGUID; var Offset:NativeInt):Boolean;
var
i : integer;
InterfaceTable: PInterfaceTable;
InterfaceEntry: PInterfaceEntry;
begin
while Assigned(AClass) do
begin
InterfaceTable := AClass.GetInterfaceTable;
if Assigned(InterfaceTable) then
begin
for i := 0 to InterfaceTable.EntryCount-1 do
begin
InterfaceEntry := @InterfaceTable.Entries[i];
if InterfaceEntry.IID=GUID then
begin
Offset:=InterfaceEntry.IOffset;
Exit(True);
end;
end;
end;
AClass := AClass.ClassParent;
end;
end;
下面我們看下通過偏移量的快速獲得對象的接口,以及通過接口快速獲取對象:
快速獲取對象的接口:
type
TSomeObject=class(TXXX, ISomeInterface)
......
end;
var
FItemObjectOffset:NativeInt;
//獲取偏移量
FindInterface(TSomeObject, ISomeInterface, FItemObjectOffset)
var
P:TSomeObject;
Intf:ISomeInterface;
....................................
//通過對象直接獲取接口
PNativeInt(@Intf)^:=PNativeInt(@P)^+ FItemObjectOffset;
Intf._AddRef;
快速通過接口獲取對象
type TSomeObject=class(TXXX, ISomeInterface) ...... end; var FItemObjectOffset:NativeInt; //獲取偏移量 FindInterface(TSomeObject, ISomeInterface, FItemObjectOffset) var P:TSomeObject; Intf:ISomeInterface; .................................... //通過接口獲取對象 P:=TSomeObject(Pointer(PNativeInt(@Intf)^- FItemObjectOffset));
