According to the Delphi docs, I can cast a TInterfacedObject to an interface using the as operator.
But it doesn't work for me. The cast gives a compile error: "Operator not applicable to this operand type".
I'm using Delphi 2007.
Here is some code (a console app). The line that contains the error is marked.
program Project6;
{$APPTYPE CONSOLE}
uses
SysUtils;
type
IMyInterface = interface
procedure Foo;
end;
TMyInterfacedObject = class(TInterfacedObject, IMyInterface)
public
procedure Foo;
end;
procedure TMyInterfacedObject.Foo;
begin
;
end;
var
o: TInterfacedObject;
i: IMyInterface;
begin
try
o := TMyInterfacedObject.Create;
i := o as IMyInterface; // <--- [DCC Error] Project6.dpr(30): E2015 Operator not applicable to this operand type
except
on E:Exception do
Writeln(E.Classname, ': ', E.Message);
end;
end.
Quick answer
Your interface needs to have a GUID for the as operator to work. Go to the first line after IMyInterface = interface, before any method definitions and hit Ctrl+G to generate a new GUID.
Longer comment
The as operator for interfaces requires a GUID because it calls IUnknown.QueryInterface, and that in turn requires a GUID. That's all right if you run into this problem when casting an INTERFACE to an other kind of INTERFACE.
You're not supposed to cast an TInterfacedObject to an interface in the first place, because that means you're holding both a reference to the implementing object (TInterfacedObject) and a reference to the implemented interface (IMyInterface). That's problematic because you're mixing two lifecycle management concepts: TObject live until something calls .Free on them; You're reasonably sure nothing calls .Free on your objects without your knowledge. But interfaces are reference-counted: when you assign your interface to a variable the reference counter increases, when that instance runs out of scope (or is assigned something else) the reference counter is decreases. When the reference counter hits ZERO the object is disposed of (.Free)!
Here's some innocent-looking code that's going to get into a real lot of trouble fast:
procedure DoSomething(If: IMyInterface);
begin
end;
procedure Test;
var O: TMyObjectImplementingTheInterface;
begin
O := TMyObjectImplementingTheInterface.Create;
DoSomething(O); // Works, becuase TMyObject[...] is implementing the given interface
O.Free; // Will likely AV because O has been disposed of when returning from `DoSomething`!
end;
The fix is very simple: Change the O's type from TMyObject[...] to IMyInterface, like this:
procedure DoSomething(If: IMyInterface);
begin
end;
procedure Test;
var O: IMyInterface;
begin
O := TMyObjectImplementingTheInterface.Create;
DoSomething(O); // Works, becuase TMyObject[...] is implementing the given interface
end; // `O` gets freed here, no need to do it manually, because `O` runs out of scope, decreases the ref count and hits zero.
If you want to use the As or Supports operator you need to add a Guid to the Interface, example:
type
IMyInterface = interface
['{00000115-0000-0000-C000-000000000049}']
procedure Foo;
end;
See the docwiki
The cast will be automatic of you define the object o as the correct type. Otherwise, you can always use supports() and/or call QueryInterface yourself.
var
o: TMyInterfacedObject;
i: IMyInterface;
begin
try
o := TMyInterfacedObject.Create;
i := o;
except
on E:Exception do
Writeln(E.Classname, ': ', E.Message);
end;
end.
Related
Let's say that I have:
type
TClassA = class
function prova: integer; virtual;
function provaSuA: integer; virtual;
end;
type
TClassB = class(TClassA)
function prova: integer; override;
function provaSuB: integer; virtual;
end;
Then I use this code:
procedure TForm1.Button1Click(Sender: TObject);
var a: TClassA;
b: TClassB;
begin
Memo1.Clear;
a := TClassB.Create;
try
b := ?? //dynamic_cast on C++
Memo1.Lines.Add(a.prova.ToString);
Memo1.Lines.Add(b.provaSuB.ToString);
finally
a.Free;
end;
end;
I am using polymorphism and the static type of a is TClassA but the dynamic type is TClassB. Of course I can only call on a methods that are declared on TClassA (or that are overridden in TClassB).
If I want to use a and have access to ALL methods in TClassB in C++ I'd use a dynamic_cast that is (together with typeid) in C++ RTTI. How can I use Delphi's RTTI to do that?
Delphi "RTTI" has a slightly different meaning from C++'s one. To replicate what dynamic_cast does, you need to follow one of the two patterns:
pattern 1: if the cast fails, I want an exception: this is achieved, by using the as operator which performs the proper type-checking and then casts the object when possible. In case of failure, a ClassCastException is thrown.
b:= a as TClassB;
pattern 2: if the cast fails, I want to handle it manually: this is achieved by using the is operator which strictly performs the test about the cast. Then you are need to manually cast (look comments in code) on success:
if (a is TClassB) then
begin
// this is a cast, however, in this context, you are simply interpreting
// the memory pointed by a as a class of type ClassB. You are not using any operator.
b:= TClassB(a);
end
else
begin
// here you know that a cannot be cast to TClassB, therefore you can gracefully take
// proper action here, without catching any exception
end;
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.
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.
Here are my types...
unit unitTestInterfaces;
interface
type
IFoo = interface
['{169AF568-4568-429A-A8F6-C69F4BBCC6F0}']
function TestFoo1:string;
function TestFoo:string;
end;
IBah = interface
['{C03E4E20-2D13-45E5-BBC6-9FDE12116F95}']
function TestBah:string;
function TestBah1:string;
end;
TFooBah = class(TInterfacedObject, IFoo, IBah)
//IFoo
function TestFoo1:string;
function TestFoo:string;
//IBah
function TestBah1:string;
function TestBah:string;
end;
implementation
{ TFooBah }
function TFooBah.TestBah: string;
begin
Result := 'TestBah';
end;
function TFooBah.TestBah1: string;
begin
Result := 'TestBah1';
end;
function TFooBah.TestFoo: string;
begin
Result := 'TestFoo';
end;
function TFooBah.TestFoo1: string;
begin
Result := 'TestFoo1';
end;
end.
And here is my code to run the example...
var
fb:TFooBah;
f:IFoo;
b:IBah;
begin
try
fb := TFooBah.Create;
/// Notice we've used IBah here instead of IFoo, our writeln() still outputs the
/// result from the TestBah() function, presumably because it's the "first" method
/// in the IBah interface, just as TestFoo1() is the "first" method in the IFoo
/// interface.
(fb as IUnknown).QueryInterface(IBah,f); //So why bother with this way at all??
//f := fb as IBah; //causes compile error
//f := fb; //works as expected
if Assigned(f)then
begin
writeln(f.TestFoo1); //wouldn't expect this to work since "f" holds reference to IBah, which doesn't have TestFoo1()
end;
(fb as IUnknown).QueryInterface(IBah,b);
if Assigned(f) then
begin
writeln(b.TestBah1);
end;
except on E:Exception do
writeln(E.Message);
end;
end.
It seems that in the first call to QueryInterface, even though we are assigning the wrong type of interface to the "f" variable, it will still try to execute the 'first' method of whatever it's pointing to, as opposed to the method with the name "TestFoo1". Using f := fb works as expected, so is there a reason we would ever use QueryInterface instead of the syntax f := fb?
I guess you are breaking the rules here:
QueryInterface will put the interface into f which you requested. You are responsible that f is of the appropriate type. As the second parameter is untyped the compiler cannot warn you about your fault.
I would argue that the better syntax is neither the QueryInterface one nor the f := fb one. It is the one you commented out:
f := fb as IBah; //causes compile error
and that is precisely because it has type checking, which covers the problem with QueryInterface that it doesn't check its arguments.
Please note that f := Fb as IFoo, the call Supports( Fb, IFoo ) etc tec all call QueryInterface in the background. So the QueryInterface method is used but you get the nice syntax with autocasting, is, as and methods like support.
This should be a simple answer, i believe its going to be a no,
but taken from a larger project, i have an interface and the procedure
iMyUnknown= interface(IInterface)
['..GUID..']
end;
procedure WorkObject(iObj :iMyUnknown);
i know this works
var
MyUnknown : iMyUnknown;
begin
if supports(obj, iMyUnknown, MyUnknown) then
WorkObject(MyUnknown);
But is it possible to do something like this?
if supports(obj, iMyUnknown) then
WorkObject(obj as iMyUnknown);
Why would you need to cast?
If obj supports the interface, and all you need to do is check that before passing it to a procedure, you can simply pass the object itself. The compiler will take care of the rest. You only need the third param on the Supports call if you want to access methods of the interface.
Compile and run the code below. It should compile without errors and present you with a console window and a dialog message.
program Project1;
{$APPTYPE CONSOLE}
uses
Classes
, Dialogs
, SysUtils
;
type
iMyUnknown = interface(IInterface)
['{DA867EBA-8213-4A91-8E03-1AACA150CE77}']
procedure DoSomething;
end;
TMuster = class(TInterfacedObject, iMyUnknown)
procedure DoSomething;
end;
procedure WorkObject(iObj: iMyUnknown);
begin
if Assigned(iObj) then ShowMessage('Got something');
end;
{ TMuster }
procedure TMuster.DoSomething;
begin
beep;
end;
var
obj: TMuster;
begin
try
obj := TMuster.Create;
if Supports(obj, iMyUnknown) then
WorkObject(obj);
except
on E:Exception do
Writeln(E.Classname, ': ', E.Message);
end;
end.
Yes, you can. The as operator worked with interfaces ever since the support for interfaces has been added to the language (around Delphi 3, IIRC). The code you posted works. Where is the problem?
You can cast an object to an interface with an as-cast, as long as the compiler knows that your object supports IInterface, and your interface has a GUID. So it won't work with TObject, but with TInterfacedObject it will.