PDA

View Full Version : Any generic type information mechanism for Delphi and FPC??



cronodragon
16-03-2008, 08:55 PM
I have a tree data structure, and need to connect each node to the properties of objects of many different classes. I should make the connection with pointers. I know there is RTTI in Delphi, but how do I deal with this problem in FPC/Lazarus? :?

Thanks!
-Marco

Robert Kosek
17-03-2008, 12:30 PM
My only suggestion for you, having considered this situation myself, is that you might descend all the objects from a single parent object type in which you store general class info. This way any class initializes and sets the generic info, which can then be read without knowledge of its type.

IIRC, FPC does have some capability to retrieve generic information, RTTI-like, but I don't remember how. It might be in the manuals.

cronodragon
17-03-2008, 02:55 PM
Thanks! Yes, it seems there is no other way around. And after considering a little more my situation I found that I can't use pointers neither, since I need to Set/Get the properties. Also I would need to call functions, procedures, etc. The only way I can think on is creating an interfacing function, and implementing it for every single object. Fortunately I descended every object from a common custom object very early in the development of my engine :D

Robert Kosek
17-03-2008, 03:04 PM
You needn't make an interface, I don't think. What I'd suggest is:
type
TMyBaseObj = class
end;
PMyBaseObj = ^TMyBaseObj;

Then you can make an array of PMyBaseObj, test it for nil or assigned, and then dereference the pointer any time you want. No interface needed! You can also typecast the dereferenced pointer in a:
with MyObj^ as TMySubObj do begin
Health := 0;
Color := clUgly;
end;And so on. Or, you could have a variable of the given type and then dereference and typecast into it. Thankfully there are a great many ways to do this!

The only time you need to do an interface type is when you're passing objects from a DLL into an application. (Found that out the hardest way: lots of crashing.)

I thought of some of this stuff while contemplating a template system for a game. That sort of thing can get a bit messy, since any given template may have variable information. So I pondered on it for a good bit and these two posts are the conclusion I came down to. Unless you wanted to go for a hashlist type. ;)

Chebmaster
28-03-2008, 07:48 AM
PMyBaseObj = ^TMyBaseObj;
Why bother? Any class fields already are pointers.

When you have
var
A, B: TMyBaseObj;
...
B.SomeField:= A;
-- it is a poiner operation.
You can call Assigned() on A, B, or B.SomeField, cast them to pointer or assign nil to them.

The construct
var
A: TMyBaseObject = nil;
is pretty valid.