How do I determine if a unit has been compiled into a Delphi program?

后端 未结 2 548
囚心锁ツ
囚心锁ツ 2020-12-29 09:08

I want to be able to determine if a particular unit has been compiled into a Delphi program, e.g. the unit SomeUnitName is part of some of my programs but not of others. I w

2条回答
  •  隐瞒了意图╮
    2020-12-29 09:25

    Unit names are compiled into the 'PACKAGEINFO' resource where you can look it up:

    uses
      SysUtils;
    
    type
      PUnitInfo = ^TUnitInfo;
      TUnitInfo = record
        UnitName: string;
        Found: PBoolean;
      end;
    
    procedure HasUnitProc(const Name: string; NameType: TNameType; Flags: Byte; Param: Pointer);
    begin
      case NameType of
        ntContainsUnit:
          with PUnitInfo(Param)^ do
            if SameText(Name, UnitName) then
              Found^ := True;
      end;
    end;
    
    function IsUnitCompiledIn(Module: HMODULE; const UnitName: string): Boolean;
    var
      Info: TUnitInfo;
      Flags: Integer;
    begin
      Result := False;
      Info.UnitName := UnitName;
      Info.Found := @Result;
      GetPackageInfo(Module, @Info, Flags, HasUnitProc);
    end;
    

    To do this for the current executable pass it HInstance:

    HasActiveX := IsUnitCompiledIn(HInstance, 'ActiveX');
    

    (GetPackageInfo enumerates all units which may be inefficient for executables with many units, in that case you can dissect the implementation in SysUtils and write your own version which stops enumerating when the unit is found.)

提交回复
热议问题