简体   繁体   English

如何检查传递的参数是否为class?

[英]How to check if passed argument is class?

I have function (written in Delphi 7, 32-bit): 我有功能(用Delphi 7,32位编写):

Function GetVMTAddr(var C): Integer;
Begin
  Result := Integer(C);
  Try
    PVmt(Result)^.SelfPtr := PVmt(C)^.SelfPtr;
  Except
    Result := 0;
  End;
End;

Which returns VMT Address (I think it is VMT, I'm not sure) and checks if parameter is an object (by try...except , which is imho poor solution). 哪个返回VMT地址(我认为它是VMT,我不确定)并检查参数是否是一个对象(通过try...except ,这是非常糟糕的解决方案)。
I have two questions: 我有两个问题:
1) Is this really VMT address or I'm wrong? 1)这真的是VMT地址还是我错了?
2) Is there any better solution to check that parameter is an object? 2)有没有更好的解决方案来检查参数是否为对象?

The argument C will hold a VMT address if what you pass to it is a class reference (aka a metaclass). 如果传递给它的是一个类引用(也就是元类),则参数C将保存VMT地址。

The condition you check in the function is useless. 您在该功能中检查的条件是无用的。 It checks whether a certain region of memory is writable, and that's all. 它检查某个内存区域是否可写,这就是全部。 If you were checking whether the SelfPtr field was equal to the value itself, then you'd be closer. 如果您正在检查 SelfPtr字段是否等于值本身,那么您就更接近了。 Something like this: 像这样的东西:

if PVmt(C).SelfPtr = C then
  Result := C;

What you're asking is very similar to a question asked here a few years ago, where someone wanted to know how to detect the type of a variable . 您所问的与几年前在这里提出的问题非常相似,有人想知道如何检测变量的类型 As I explained then, if you've gotten to the point where you think you need to use this code, you're already in trouble. 正如我之前解释的那样,如果你已经达到了认为需要使用此代码的程度,那么你已经遇到了麻烦。 Go back and change your design so that you can know whether you have a class reference or an object reference instead of having to guess. 返回并更改您的设计,以便您可以知道您是否有类引用或对象引用而不必猜测。

If you really have to guess, then you can try using the functions provided by the JCL, IsClass and IsObject . 如果你真的需要猜测,那么你可以尝试使用JCL, IsClassIsObject提供的函数。 They do the same guessing that your code attempts to use, but they do it right. 他们做同样的猜测,你的代码试图使用,但他们做得对。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM