韩小明@xiammy的专栏

没水的地方挖井,有水的地方修渠

原创 JCL中由接口获得对象的方法收藏

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

//=== Interface information ==================================================

function GetImplementorOfInterface(
const I: IInterface): TObject;
{ TODO -cDOC : Original code by Hallvard Vassbotn }
{ TODO -cTesting : Check the implemetation for any further version of compiler }
const
  AddByte 
= $04244483// opcode for ADD DWORD PTR [ESP+4], Shortint
  AddLong = $04244481// opcode for ADD DWORD PTR [ESP+4], Longint
type
  PAdjustSelfThunk 
= ^TAdjustSelfThunk;
  TAdjustSelfThunk 
= packed record
    
case AddInstruction: Longint of
      AddByte: (AdjustmentByte: ShortInt);
      AddLong: (AdjustmentLong: Longint);
  end;
  PInterfaceMT 
= ^TInterfaceMT;
  TInterfaceMT 
= packed record
    QueryInterfaceThunk: PAdjustSelfThunk;
  end;
  TInterfaceRef 
= ^PInterfaceMT;
var
  QueryInterfaceThunk: PAdjustSelfThunk;
begin
  
try
    Result :
= Pointer(I);
    
if Assigned(Result) then
    begin
      QueryInterfaceThunk :
= TInterfaceRef(I)^.QueryInterfaceThunk;
      
case QueryInterfaceThunk.AddInstruction of
        AddByte:
          Inc(PChar(Result), QueryInterfaceThunk.AdjustmentByte);
        AddLong:
          Inc(PChar(Result), QueryInterfaceThunk.AdjustmentLong);
      
else
        Result :
= nil;
      end;
    end;
  except
    Result :
= nil;
  end;
end;

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

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

发表于 @ 2007年05月15日 21:43:00|评论(loading...)

新一篇: P2P!别赚老大的钱 | 旧一篇: 访问量到20万,自贺一把

用户操作
[即时聊天] [发私信] [加为好友]
韩小明
订阅我的博客
XML聚合  FeedSky
韩小明的公告
作者毕业于浙江大学,非常热爱体育运动。现在尤其热爱羽毛球运动。在休息时间非常热爱技术文章写作。
最近垃圾评论泛滥,为了不污染大家的视听,暂时关闭评论,请大家理解。
欢迎转载,但请注意,除非特别声明,本站采用Creative Commons License许可:署名,非商业。

文章分类
收藏
    链接
    宗刚的专栏(RSS)
    快乐学习(RSS)
    陈亮亮的专栏(RSS)
    朋友
    张恂论 OO
    橘子懒懒的BLOG(RSS)
    言之有李(RSS)
    赵伟的小家
    存档
    Csdn Blog version 3.1a
    Copyright © 韩小明