I have proved that I can get the name of an interface from its GUID using Delphi 2010 (eg IMyInterface converted to the string 'IMyInterface'. I'd like to achieve this in Delphi 7 (for compatibility). Is this possible? Or are there fundamental compiler limitations.
Yes you can get it, the following shows using the IExample type how you can get the name.
The old Delphi 7 RTTI was done through the TypInfo Unit.
program Project6;
{$APPTYPE CONSOLE}
uses
SysUtils,TypInfo;
type
IExample = interface
['{4902F666-F3FC-4999-BD8C-F226851201D6}']
procedure blah;
end;
begin
Writeln(GetTypeName(TypeInfo(IExample)));
readln
end.
Just noticed you said you wanted to get it from the GUID and not just the type. This would require a registry of GUID to types. The RTTI in Delphi 7 can be used to get the type.
The following will take IExample return the guid.
Writeln(GUIDToString(GetTypeData(TypeInfo(IExample)).Guid));
Here is an example registry that would Map TypeInfo() of an Interface to it's GUID.
It could be optimized but I did it to illustrate the concept.
unit Unit11;
interface
uses
TypInfo,SysUtils, Contnrs;
type
TGuidMap = class(TObject)
Guid : TGUID;
TypeInfo : PTypeInfo;
end;
procedure RegisterInterface(InterfaceType : PTypeInfo);
function GetInterfaceType(Guid : TGUID) : PTypeInfo;
implementation
var
GuidMapList : TObjectList;
procedure RegisterInterface(InterfaceType : PTypeInfo);
var
Map : TGuidMap;
begin
Map := TGuidMap.Create;
Map.TypeInfo := InterfaceType;
Map.Guid := GetTypeData(InterfaceType).Guid;
GuidMapList.Add(Map);
end;
function GetInterfaceType(Guid : TGUID) : PTypeInfo;
var
I : Integer;
begin
result := nil;
for I := 0 to GuidMapList.Count - 1 do
begin
if IsEqualGUID(TGuidMap(GuidMapList.Items[I]).Guid,Guid) then
begin
result := TGuidMap(GuidMapList.Items[I]).TypeInfo;
break;
end;
end;
end;
Initialization
GuidMapList := TObjectList.Create(true);
finalization
GuidMapList.Free;
end.
To Add an item to the registry you would then call
RegisterInterface(TypeInfo(IExample));
In Delphi 7 you should build your own mapping from GUID to RTTI (or Name). THere is no RTTI context like in Delphi 2010. I use RIIT extensively and usually "register" all interesting types in the initialization section of the unit somewhere central and find all types from there based upon the typeinfo pointer. This works for D7, D2007 and D2010 (but is more work if you need to create it). Also you might forget to register a type and wonder why o why something cannot be found.
Related
I'm doing a simple class definition in Delphi and I wanted to use a TStringList in the class & it's constructor (so everytime you create an object, you pass it a StringList and it does some magic stuff to the StringList data, copying the string list to it's own internal string list). The problem I get is that when I try to declare what it "uses" before the class definition (so it knows how to handle the TStringList), it fails on compile. But without that, it doesn't know what a TStringList is. So it seems to be a scoping issue.
Below is a (very simplified) class definition, similar to what I'm trying to do. Can someone suggest how I can make this work and get the scoping right?
I tried adding the uses statements at the project level as well, but it still fails. I wonder what I need to do to get this right.
unit Unit_ListManager;
interface
type
TListManager = Class
private
lmList : TStringList;
procedure SetList;
published
constructor Create(AList : TStringList);
end;
implementation
uses
SysUtils,
StrUtils,
Vcl.Dialogs;
constructor TBOMManager.Create(AList : TStringList);
begin
lmList := TStringList.Create;
lmList := AListList;
end;
procedure SetPartsList(AList : TStringList);
begin
lmList := AListList;
ShowMessage('Woo hoo, got here...');
end;
end.
Kind Regards
You didn't show where exactly you were adding the unit reference, but I'm betting it was the wrong place. Take note of the additional code between interface and type.
I've also corrected your definition of the constructor, which you had placed in published instead of public. Only property items belong in the published section.
unit Unit_ListManager;
interface
uses
Classes,
SysUtils,
StrUtils,
Vcl.Dialogs;
type
TListManager = Class
private
lmList : TStringList;
procedure SetList;
public
constructor Create(AList : TStringList);
end;
implementation
constructor TListManager.Create(AList : TStringList);
begin
inherited Create; // This way, if the parent class changes, we're covered!
// lmList := TStringList.Create; This would produce a memory leak!
lmList := AListList;
end;
procedure TListManager.SetList;
begin
// You never provided an implementation for this method
end;
end.
I am having a strange problem of using interface in different versions of Delphi. The following minimized code compiles and runs as expected in Delphi XE and higher but not in Delphi 7. Specificaly, it seems when compiling in Delphi 7, the function TForm1.Load: IMoleculeSubject; does not returns the correct result, i.e., the correct reference to the newly created instance. Could you help to comment about the reason and possible workaround? Many thanks!
uInterface.pas
unit uInterface;
interface
type
IMoleculeSubject = interface
['{BEB4425A-186C-45DF-9DCE-C7175DB0CA90}']
end;
TMoleculeSubject = class(TInterfacedObject, IMoleculeSubject)
end;
implementation
end.
uBusiness.pas
unit uBusiness;
interface
uses
uInterface;
type
TMoleculeDecorator = class(TMoleculeSubject)
private
FID: Integer;
public
property ID: Integer read FID;
constructor Create;
end;
implementation
{ TMoleculeDecorator }
constructor TMoleculeDecorator.Create;
begin
inherited Create;
FID := Random(100);
end;
end.
Unit1.pas
unit Unit1;
interface
uses
uInterface, uBusiness,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,
Forms, Dialogs;
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
private
function Load: IMoleculeSubject;
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var
MolSubject: IMoleculeSubject;
begin
MolSubject := Load;
// The down-cast is to show the returned result is wrong in Delphi 7!
Caption := IntToStr(TMoleculeDecorator(MolSubject).ID);
end;
function TForm1.Load: IMoleculeSubject;
var
MolSubject: IMoleculeSubject;
begin
MolSubject := TMoleculeDecorator.Create;
Result := MolSubject;
end;
end.
The Load function works perfectly well in all versions of Delphi. The problem is your cast, which is what is known as an unsafe typecast. An unsafe typecast from an interface reference to an object has ill-defined behaviour in older versions of Delphi. However, the behaviour is well-defined in modern Delphi. The documentation says more.
So, the basic problem is that your expectations for the behaviour are not compatible with the Delphi 7 version of the language.
If you get the interface to return the ID you will find that the interface you are creating is as expected.
program InterfaceDemo;
{$APPTYPE CONSOLE}
uses
Classes;
type
IMyIntf = interface
function GetID: Integer;
end;
TImplementingObject = class(TInterfacedObject, IMyIntf)
private
FID: Integer;
function GetID: Integer;
public
constructor Create;
end;
{ TImplementingObject }
constructor TImplementingObject.Create;
begin
FID := Random(100);
Writeln(FID);
end;
function TImplementingObject.GetID: Integer;
begin
Result := FID;
end;
var
MyIntf: IMyIntf;
begin
Randomize;
MyIntf := TImplementingObject.Create;
Writeln(MyIntf.GetID);
Readln;
end.
It's rather unusual to ask for the implementing object from an interface. To do so suggests that there is a problem with your design. Should you really need to do so there are a few options:
In modern Delphi you can use the type-safe case with the as operator.
In older Delphi versions there are hacks that retrieve the implementing object: Casting a delphi interface to its implementation class without modifying the interface
You could add a function to the interface that returns the implementing object.
The latter option works in all versions of Delphi and does so without resorting to subterfuge.
Casting interfaces to objects is available since Delphi 2010. Where are workarounds for older Delphi versions, see for example How to cast a Interface to a Object in Delphi
I'm trying to get hold of an object using TRttiContext.FindType(QualifiedTypeName). Here's what I've got:
program MissingRTTI;
{$APPTYPE CONSOLE}
uses System.SysUtils, RTTI, Classes;
type
TMyClass = class(TObject) end;
var
rCtx: TRttiContext;
rType: TRttiInstanceType;
begin
rCtx := TRttiContext.Create();
rType := rCtx.GetType(TypeInfo(TMyClass)) as TRttiInstanceType;
if (rType <> nil) then begin
WriteLn('Type found using TypeInfo');
end;
rType := rCtx.FindType(TMyClass.QualifiedClassName) as TRttiInstanceType;
if (rType <> nil) then begin
WriteLn('Type found using qualified class name.');
end;
ReadLn;
rCtx.Free();
end.
Unfortunately, only rCtx.GetType seems to find the desired type. (I've also tried to list all types using GetTypes. The desired type does not appear in the resulting array.) Anyone know how to force the compiler to emit RTTI for this type?
Your call to the FindType method doesn't return Rtti info because this function works only for public types. So if you check the rType.IsPublicType property the value returned is false .
The public types must be declarated in the interface section of a unit (to be recognized as public). So if you move the TMyClass class definition to the interface part of a unit you will able to use the FindType without problems.
I've recently posted a question in this forum asking for any advice regarding missing RTTI information in a DXE2 executable.
That post was a stripped down version of my actual case. RRUZ came to the rescue, and so the stripped down version was quickly resolved. The original problem, though, is still standing, and so I'm posting it in full now. "Main":
program MissingRTTI;
{$APPTYPE CONSOLE}
uses
System.SysUtils, RTTI, MyUnit in 'MyUnit.pas', RTTIUtil in 'RTTIUtil.pas';
var
RHelp: TRttiHelper;
begin
RHelp := TRttiHelper.Create();
if (RHelp.IsTypeFound('MyUnit.TMyClass')) then WriteLn('TMyClass was found.')
else WriteLn('TMyClass was not found.');
ReadLn;
RHelp.Free();
end.
RTTIUtil.pas:
unit RTTIUtil;
interface
uses
MyUnit;
type
TRttiHelper = class(TObject)
public
function IsTypeFound(TypeName: string) : boolean;
end;
implementation
uses
RTTI;
function TRttiHelper.IsTypeFound(TypeName: string): boolean;
var
rCtx: TRttiContext;
rType: TRttiType;
begin
Result := false;
rCtx := TRttiContext.Create();
rType := rCtx.FindType(TypeName);
if (rType <> nil) then
Result := true;
rCtx.Free();
end;
end.
and finally MyUnit.pas:
unit MyUnit;
interface
type
TMyClass = class(TObject)
end;
implementation
end.
The desired type is not found. However, if I change TRttiHelper.IsTypeFound so that it instantiates (and immediately frees) an instance of TMyClass, the type is found. Like so:
function TRttiHelper.IsTypeFound(TypeName: string): boolean;
var
rCtx: TRttiContext;
rType: TRttiType;
MyObj: TMyClass;
begin
Result := false;
MyObj:= TMyClass.Create();
MyObj.Free();
rCtx := TRttiContext.Create();
...
So I'm wondering, is there any way I can force RTTI to be emitted for TMyClass without actually instantiating it?
Update:
On a side not, I might mention that if I try to fetch the TRttiType using TRttiContext.GetType, the desired type is found. So there is some RTTI emitted. Checking the TRttiType.IsPublic property as retrieved by TRttiContext.GetType yields a true value, i.e. the retrieved type is public (and hence should be possible to locate using TRttiContext.FindType).
Add a reference to the class and make sure that the compiler/linker cannot strip it from the executable.
unit MyUnit;
interface
type
TMyClass = class(TObject)
end;
implementation
procedure ForceReferenceToClass(C: TClass);
begin
end;
initialization
ForceReferenceToClass(TMyClass);
end.
In production code you would want to place ForceReferenceToClass in a base unit so that it could be shared. The initialization section of the unit that declares the class is the most natural place for the calls to ForceReferenceToClass since the unit is then self-contained.
Regarding your observation that GetType can locate the type, the very act of calling GetType(TMyClass) adds a reference to the type to the program. It's not that the RTTI is present and FindType cannot find it. Rather, the inclusion of GetType(TMyClass) adds the RTTI to the resulting program.
I used {$STRONGLINKTYPES ON} and worked very well. Put it on main unit.
for a framework I wrote a wrapper which takes any object, interface or record type to explore its properties or fields. The class declaration is as follows:
TWrapper<T> = class
private
FType : TRttiType;
FInstance : Pointer;
{...}
public
constructor Create (var Data : T);
end;
In the constructor I try to get the type information for further processing steps.
constructor TWrapper<T>.Create (var Data : T);
begin
FType := RttiCtx.GetType (TypeInfo (T));
if FType.TypeKind = tkClass then
FInstance := TObject (Data)
else if FType.TypeKind = tkRecord then
FInstance := #Data
else if FType.TypeKind = tkInterface then
begin
FType := RttiCtx.GetType (TObject (Data).ClassInfo); //<---access violation
FInstance := TObject (Data);
end
else
raise Exception.Create ('Unsupported type');
end;
I wonder if this access violation is a bug in delphi compiler (I'm using XE).
After further investigation I wrote a simple test function, which shows, that asking for the class name produces this exception as well:
procedure TestForm.FormShow (Sender : TObject);
var
TestIntf : IInterface;
begin
TestIntf := TInterfacedObject.Create;
OutputDebugString(PChar (TObject (TestIntf).ClassName)); //Output: TInterfacedObject
Test <IInterface> (TestIntf);
end;
procedure TestForm.Test <T> (var Data : T);
begin
OutputDebugString(PChar (TObject (Data).ClassName)); //access violation
end;
Can someone explain me, what is wrong? I also tried the procedure without a var parameter which did not work either. When using a non generic procedure everything works fine, but to simplify the use of the wrapper the generic solution would be nice, because it works for objects and records the same way.
Kind regards,
Christian
Your code contains two wrong assumptions:
That you can obtain meaningful RTTI from Interfaces. Oops, you can get RTTI from interface types.
That a Interface is always implemented by a Delphi object (hence your attempt to extract the RTTI from the backing Delphi object).
Both assumptions are wrong. Interfaces are very simple VIRTUAL METHOD tables, very little magic to them. Since an interface is so narrowly defined, it can't possibly have RTTI. Unless of course you implement your own variant of RTTI, and you shouldn't. LE: The interface itself can't carry type information the way an TObject does, but the TypeOf() operator can get TypeInfo if provided with a IInterface
Your second assumption is also wrong, but less so. In the Delphi world most interfaces will be implemented by Delphi objects, unless of course you obtain the interface from a DLL written in an other programming language: Delphi's interfaces are COM-compatible, so it's implementations can be consumed from any other COM-compatible language and vice versa. But since we're talking Delphi XE here, you can use this syntax to cast an interface to it's implementing object in an intuitive and readable way:
TObject := IInterface as TObject;
that is, use the as operator. Delphi XE will at times automagically convert a hard cast of this type:
TObject := TObject(IInterface);
to the mentioned "as" syntax, but I don't like this magic because it looks very counter-intuitive and behaves differently in older versions of Delphi.
Casting the Interface back to it's implementing object is also wrong from an other perspective: It would show all the properties of the implementing object, not only those related to the interface, and that's very wrong, because you're using Interfaces to hide those implementation details in the first place!
Example: Interface implementation not backed by Delphi object
Just for fun, here's a quick demo of an interface that's not backed by an Delphi object. Since an Interface is nothing but an pointer to a virtual method table, I'll construct the virtual method table, create a pointer to it and cast the the pointer to the desired Interface type. All method pointers in my fake Virtual Method table are implemented using global functions and procedures. Just imagine trying to extract RTTI from my i2 interface!
program Project26;
{$APPTYPE CONSOLE}
uses
SysUtils;
type
// This is the interface I will implement without using TObject
ITestInterface = interface
['{CFC4942D-D8A3-4C81-BB5C-6127B569433A}']
procedure WriteYourName;
end;
// This is a sample, sane implementation of the interface using an
// TInterfacedObject method
TSaneImplementation = class(TInterfacedObject, ITestInterface)
public
procedure WriteYourName;
end;
// I'll use this record to construct the Virtual Method Table. I could use a simple
// array, but selected to use the record to make it easier to see. In other words,
// the record is only used for grouping.
TAbnormalImplementation_VMT = record
QueryInterface: Pointer;
AddRef: Pointer;
ReleaseRef: Pointer;
WriteYourName: Pointer;
end;
// This is the object-based implementation of WriteYourName
procedure TSaneImplementation.WriteYourName;
begin
Writeln('I am the sane interface implementation');
end;
// This will implement QueryInterfce for my fake IInterface implementation. All the code does
// is say the requested interface is not supported!
function FakeQueryInterface(const Self:Pointer; const IID: TGUID; out Obj): HResult; stdcall;
begin
Result := S_FALSE;
end;
// This will handle reference counting for my interface. I am not using true reference counting
// since there is no memory to be freed, si I am simply returning -1
function DummyRefCounting(const Self:Pointer): Integer; stdcall;
begin
Result := -1;
end;
// This is the implementation of WriteYourName for my fake interface.
procedure FakeWriteYourName(const Self:Pointer);
begin
WriteLn('I am the very FAKE interface implementation');
end;
var i1, i2: ITestInterface;
R: TAbnormalImplementation_VMT;
PR: Pointer;
begin
// Instantiate the sane implementation
i1 := TSaneImplementation.Create;
// Instantiate the very wrong implementation
R.QueryInterface := #FakeQueryInterface;
R.AddRef := #DummyRefCounting;
R.ReleaseRef := #DummyRefCounting;
R.WriteYourName := #FakeWriteYourName;
PR := #R;
i2 := ITestInterface(#PR);
// As far as all the code using ITestInterface is concerned, there is no difference
// between "i1" and "i2": they are just two interface implementations.
i1.WriteYourName; // Calls the sane implementation
i2.WriteYourName; // Calls my special implementation of the interface
WriteLn('Press ENTER to EXIT');
ReadLn;
end.
Two possible answers.
If this always happens, even when T is an object, then it's a compiler error and you ought to file a QC report about it. (With Interfaces, the cast-an-interface-to-an-object thing requires some black magic from the compiler, and it's possible that the generics subsystem doesn't implement it properly.)
If you're taking a T that's not an object, though, such as a record type, and getting this error, then everything's working as designed; you're just using typecasts improperly.
Either way, there's a way to get RTTI information out of any arbitrary type. You know how TRttiContext.GetType has two overloads? Use the other one. Instead of calling GetType (TObject (Data).ClassInfo), try calling GetType(TypeInfo(Data)).
Oh, and declare FInstance as a T instead of a pointer. It'll save you a lot of hassle.