RTTI Free on an object created by Invoke

0

I am creating a routine to instantiate a class via RTTI and validate if this class implements a interface .

I have a test class implemented as follows:

unit teste.classeTeste.uclasseTeste;
interface
uses
  validador;
type
  ClasseTeste = class(TInterfacedObject, IServico)
    private
    public
      function foo: string;
  end;
implementation
{ classe }
function ClasseTeste.foo: string;
begin
  Result := 'Teste foo';
end;
initialization
  ClasseTeste.ClassName;
end.

And I have a Validator class implemented as follows:

unit validador;
interface    
uses
  Rtti;
type
  IServico = interface
  ['{46C26FED-AEDD-456F-B182-DEECB780D264}']
  end;
  Svc = class
    public
      function Validar(pClassName: string): Boolean;
  end;
implementation
uses
  SysUtils;
{ Svc }
function Svc.Validar(pClassName: string): Boolean;
var
  lContext: TRttiContext;
  lType: TRttiInstanceType;
  lObj: TObject;
begin
  Result := False;
  lType := lContext.FindType(pClassName) as TRttiInstanceType;
  if lType = nil then
    raise Exception.Create('Classe solicitada não encontrada no sistema ou ClassNameInválido');
  lObj := lType.GetMethod('Create').Invoke(lType.MetaclassType, []).AsObject;
  try
    if not Supports(lObj, IServico) then
      raise Exception.Create('A classe serviço não implementa a interface IServico!');
  finally
    lObj.Free;
  end;
  Result := True;
end;
end.

The question is: In the Validate method on the

'lObj.Free';

It bursts

  

"Invalid Pointer Operation".

Theoretically I have a TObject instantiated. It needs to be released sometime. How and when do I release it?

Note: I'm using Delphi 2010.

    
asked by anonymous 26.01.2016 / 11:47

1 answer

0

The problem is in line if not Supports(lObj, IServico) then

When the Supports function is called it releases lObj and as you call free always

finally
   lObj.Free;
end;

It tries to release again, causing the error, take the test, implement the method

destructor Destroy; override;

in your ClassTest class and you will see that it calls Free twice.

    
08.02.2016 / 18:57