I've written a function that accepts a class type (T) and an interface type (I) and returns an interface (I) to the object (T). Here's the code.
interface
function CreateObjectInterface<T: Class, constructor; I: IInterface>(
out AObject: TObject): I;
...
implementation
function TORM.CreateObjectInterface<T, I>(out AObject: TObject): I;
begin
AObject := T.Create;
if not Supports(AObject, GetTypeData(TypeInfo(I))^.Guid, Result) then
begin
AObject.Free;
AObject := nil;
raise EORMUnsupportedInterface.CreateFmt(
'Object class "%s" does not support interface "%s"',
[AObject.ClassName, GUIDToString(GetTypeData(TypeInfo(I))^.GUID)]
);
end;
end;
The function works as expected with no memory leaks or other undesirables.
Are there other ways to achieve the same result?