如何检测Delphi类是否具有虚拟构造函数? [英] How can I detect if a Delphi class has a virtual constructor?

查看:116
本文介绍了如何检测Delphi类是否具有虚拟构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,是否有办法找出此类具有虚拟构造函数(在运行时)?

For example, is there a way to find out that this class has a virtual constructor (at runtime)?

   TMyClass = class(TObject)
     MyStrings: TStrings;
     constructor Create; virtual;   
   end;

例如,在此代码中,我想测试Clazz引用的类是否具有虚拟构造函数:

For example, in this code I would like to test if the class referenced by Clazz has a virtual constructor:

procedure Test;
var
  Clazz: TClass;
  Instance: TObject;
begin
  Clazz := TMyClass;
  Instance := Clazz.Create;
end;

是否有一个简单的解决方案,例如使用RTTI,它在Delphi 6到2009年都可以使用?

Is there a simple solution, for example using RTTI, which works in Delphi 6 to 2009?

推荐答案

在TypInfo单元中,似乎没有任何方法可以判断使用RTTI的方法是否是虚拟的。不过,如果有类参考,则可以通过检查VMT来滚动自己的方法。

Looking through the TypInfo unit, it doesn't look like there's any way to tell if a method is virtual using RTTI or not. If you have a class reference, though, you can probably roll your own method by examining the VMT.

根据艾伦·鲍尔(Allen Bauer)的回答,这个问题,您可以找到vmtClassName指向的值之前的VMT。在类引用的地址处找到第一个用户定义的虚拟方法(如果有)。换句话说, pointer(Clazz)^ 。既然您已经知道了VMT用户定义部分的起点和终点,那么进行一个while循环来比较表中的每个指针与指向Clazz.create的方法指针的Code部分就不会太困难了。强制转换为TMethod。如果您找到匹配项,则它是一种虚拟方法。如果不是,那就不是。

According to Allen Bauer, in an answer to this question, you can find the end of the VMT immediately before the value pointed to by vmtClassName. The first user-defined virtual method (if any) is found at the address of the class reference. In other words, pointer(Clazz)^. Now that you know the start and end points of the user-defined section of the VMT, it shouldn't be too difficult to make a while loop that compares each pointer in the table against the Code section of a method pointer to Clazz.create casted to a TMethod. If you get a match, then it's a virtual method. If not, then it isn't.

是的,虽然有点hack,但是可以用。如果有人能找到更好的解决方案,那么他们将获得更大的力量。

Yes, it's a bit of a hack, but it'll work. If anyone can find a better solution, more power to them.

这篇关于如何检测Delphi类是否具有虚拟构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆