I'm trying to write some generic debug code using the Delphi RTTI. The problem I have come across is that I'm examining the contents of a TList which only holds Pointers. Now I know from my code that these Pointers are in fact TObject references (or some descendant).
So my question is this: given a valid Pointer is there a safe way to determine if it is in fact a TObject reference?
There is no safe way to determine whether valid pointer is
TObjectreferenceYou can only tell with certainty that pointer is not an object reference.
Having said that, for debugging purposes there is a way to detect that pointer might be an object reference, but you may also get false positives - memory content we are inspecting may satisfy the check by pure chance.
Every object instance also holds a pointer to its class virtual method table - VMT. It also has a pointer pointing to start of its data - offset of that pointer is defined by
vmtSelfPtrconstant declared inSystemunit.Class references in
vmtSelfPtrdiffer from objects as they hold reference back to self.Above facts will tells us we are not looking at a class reference first, and then we will check whether possible object's VMT points to possible class reference.
Besides that for each pointer we will first check that it belongs to valid address space.
You can find more information about VMT here Internal Data Formats - Class Types
The code that detects whether pointer is possible object is taken from Spring4D library:
And we can use that function like:
Note:
IsValidObjectshould only be used on valid pointers - meaning pointers that point to valid allocated memory. You cannot detect whether object instance behind the pointer has been released or not.If you have following code, you will still get
TRUEas the result of theIsValidObjectcall.Note: Besides for debugging purposes,
IsValidObjectcan be safely called in release mode on any pointer you know it is eithernil, class reference, or object reference. In other words you can safely use it to distinguish between class and object references.