Reputation: 13454
I'm doing some work with RTTI in Delphi XE3 and so far, this has resulted in a call to a procedure as follows:
procedure MyProc( ARecordInstance : pointer; ARecordType : PTypeInfo );
and I call this routine as follows:
MyProc( @MyRec TypeInfo( TMyRec ));
This all works fine.
It occurs to me that I might be able to simplify my procedure to:
procedure MyProc( var ARecord ); or procedure MyProc( ARecord : pointer );
..if I can get the type info from ARecord within my procedure. Working with an 'instance' such as 'ARecord' though, TypeInfo gives 'expects a type identifier' error, which is fair. Is there any way that I can pass a single pointer reference to my record and then extract the type from it?
Thanks
Upvotes: 3
Views: 495
Reputation: 43023
Why not just code, with an un-typed var parameter:
procedure MyProc(var ARecordInstance; ARecordType : PTypeInfo);
begin
...
You will be able to call:
MyProc(MyRec,TypeInfo(TMyRec));
So avoid to type @MyRec
. But you will also do not have strong type checking.
Using generics as proposed by Remy will allow strong typing, but will generate a bit more code.
Upvotes: 0
Reputation: 595295
If you need to support multiple types, you can wrap your procedure inside of a class that has a Generic parameter, then the procedure will know what data type it is working with, eg:
type
MyClass<T> = class
public
class procedure MyProc(var AInstance : T);
end;
class procedure MyClass<T>.MyProc(var AInstance : T);
var
InstanceType: PTypeInfo;
begin
InstanceType := TypeInfo(T);
//...
end;
.
MyClass<TMyRec>.MyProc(MyRec);
Upvotes: 4