Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How test if interface exists in compile-time?

Tags:

delphi

The IDeveloperConsoleMessageReceiver interface in the MSHTML.pas unit doesn't exists in Delphi 2010, but (probably) exists in more recent versions, because it's a recent feature.

I want to manually declare this interface, but only if it doesn't already exist.

How can I test if this interface is declared?

Something like the "fake" code:

{$IFNDEF "IDeveloperConsoleMessageReceiver"}
type
  IDeveloperConsoleMessageReceiver = interface ...
{$ENDIF}
like image 930
marciel.deg Avatar asked Feb 12 '17 23:02

marciel.deg


2 Answers

What you are looking for is

{$IF not DECLARED(IDeveloperConsoleMessageReceiver)}
  IDeveloperConsoleMessageReceiver = interface ...
{$ENDIF}

More details can be found here

EDIT: Just to clarify, it will test if the symbol is declared in the scope where the $IF occurs. So even if a symbol is declared in your current project, if the unit where it is declared is not in the USES of the unit where you test it, it won't count as declared.

like image 128
Ken Bourassa Avatar answered Nov 05 '22 20:11

Ken Bourassa


You can test for predefined constants with the {$IF} compiler define:

{$IFDEF CONDITIONALEXPRESSIONS}
  {$IF MSHTMLMajorVersion < 4}  // Implement interface
    type
      IDeveloperConsoleMessageReceiver = interface ...
  {$IFEND}
{$ENDIF}

MSHTMLMajorVersion is a declared constant in MSHTML.PAS, which defines if a specific interface is declared or not:

const
  // TypeLibrary Major and minor versions
  MSHTMLMajorVersion = 4;
  MSHTMLMinorVersion = 0;

If your question is how to test if any interface exists at compile time, then unless you could not derive it from a constant, you could force the compiler to stop with an error if it is undeclared:

type
  IMyTest = IDeveloperConsoleMessageReceiver;   

This is perhaps not ideal, depending on the scope of the question.

like image 5
LU RD Avatar answered Nov 05 '22 21:11

LU RD