JCL中由接口获得对象的方法

我原本并不想单独发以下JCL的方法,可是想到很多人可能还是不知道的。另外,从我博客的回复上看,很多人也愿意去了解一下,特此贴出JCL中的代码。

<style type="text/css"> <!-- body { color: #000000; background-color: #ffffff; } .pas1-assembler { background-color: #ffffff; color: #000000; } .pas1-character { background-color: #ffffff; color: #ff00ff; } .pas1-comment { background-color: #ffffff; color: #008000; font-style: italic; } .pas1-float { background-color: #ffffff; color: #ff0000; } .pas1-hexadecimal { background-color: #ffffff; color: #ff0000; } .pas1-identifier { background-color: #ffffff; color: #000000; } .pas1-number { background-color: #ffffff; color: #ff0000; } .pas1-preprocessor { background-color: #ffffff; color: #008000; font-style: italic; } .pas1-reservedword { background-color: #ffffff; color: #000080; font-weight: bold; } .pas1-space { background-color: #ffffff; color: #000000; } .pas1-string { background-color: #ffffff; color: #ff00ff; } .pas1-symbol { background-color: #ffffff; color: #000000; } --></style>

 
     
// ===Interfaceinformation==================================================

functionGetImplementorOfInterface(
const I:IInterface):TObject;
... {TODO-cDOC:OriginalcodebyHallvardVassbotn}
... {TODO-cTesting:Checktheimplemetationforanyfurtherversionofcompiler}
const
AddByte
= $ 04244483 ; // opcodeforADDDWORDPTR[ESP+4],Shortint
AddLong = $ 04244481 ; // opcodeforADDDWORDPTR[ESP+4],Longint
type
PAdjustSelfThunk
= ^ TAdjustSelfThunk;
TAdjustSelfThunk
= packedrecord
case AddInstruction:Longintof
AddByte:(AdjustmentByte:ShortInt);
AddLong:(AdjustmentLong:Longint);
end;
PInterfaceMT
= ^ TInterfaceMT;
TInterfaceMT
= packedrecord
QueryInterfaceThunk:PAdjustSelfThunk;
end;
TInterfaceRef
= ^ PInterfaceMT;
var
QueryInterfaceThunk:PAdjustSelfThunk;
begin
try
Result:
= Pointer(I);
if Assigned(Result)then
begin
QueryInterfaceThunk:
= TInterfaceRef(I) ^ .QueryInterfaceThunk;
case QueryInterfaceThunk.AddInstructionof
AddByte:
Inc(PChar(Result),QueryInterfaceThunk.AdjustmentByte);
AddLong:
Inc(PChar(Result),QueryInterfaceThunk.AdjustmentLong);
else
Result:
= nil;
end;
end;
except
Result:
= nil;
end;
end;

注释:这段代码出自JCL代码中JclSysUtils单元中。

提示:读这段代码,要明白一个道理,在代码执行过程中,接口和对象指针的偏移是硬编码的在汇编中的。转换的过程,就是解析这段汇编的过程。

你可能感兴趣的:(css)