Note that there are some explanatory texts on larger screens.

plurals
  1. POCasting object to interface type with no TInterfacedObject as base class
    text
    copied!<p>I need a class implementing interface with no reference counting. I did the following:</p> <pre><code> IMyInterface = interface(IInterface) ['{B84904DF-9E8A-46E0-98E4-498BF03C2819}'] procedure InterfaceMethod; end; TMyClass = class(TObject, IMyInterface) protected function _AddRef: Integer;stdcall; function _Release: Integer;stdcall; function QueryInterface(const IID: TGUID; out Obj): HResult;stdcall; public procedure InterfaceMethod; end; procedure TMyClass.InterfaceMethod; begin ShowMessage('The Method'); end; function TMyClass.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE; end; function TMyClass._AddRef: Integer; begin Result := -1; end; function TMyClass._Release: Integer; begin Result := -1; end; </code></pre> <p>Lack of reference counting works fine. But my concern is that I cannot cast <code>TMyClass</code> to <code>IMyInterface</code> using <code>as</code> operator:</p> <pre><code>var MyI: IMyInterface; begin MyI := TMyClass.Create as IMyInterface; </code></pre> <p>I am given </p> <blockquote> <p>[DCC Error] E2015 Operator not applicable to this operand type</p> </blockquote> <p>The problem disappears when <code>TMyClass</code> derives from <code>TInterfacedObject</code> - i.e. I can do such casting without compiler error. Obviously I do not want to use TInterfacedObject as a base class as it would make my class reference counted. Why is such casting disallowed and how one would workaround it?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload