Search code examples
c#.netdelphiruntime

How to read the AssemblyID of an Assembly DLL using the .Net Runtime Library for Delphi?


I need to create a function that allows me to read the AssemblyID directly from the Assembly DLL. I need this to register generically different assembly:

TClrAssembly.RegisterDLLAssembly(AssemblyGuid, AssemblyLocation, ltfileLocation); 

Unfortunately my own solution does not work, because with certain DLLs the GuidAttribute is missing in the list of CustomAttributesData. For other DLLs I see this GuidAttribute but the content does not match the expected GUID.

This is my code:

function GUIDFromAssembly(AssemblyFileName: string): string;
var
  InspectedAssembly: _Assembly;
  GenericList: _GenericIList;
  GenericItems: _GenericICollection;
begin
  result := '';
  InspectedAssembly:= CoAssemblyHelper.CreateInstance.ReflectionOnlyLoadFrom(AssemblyFileName); 
  if not assigned(InspectedAssembly) then
    raise Exception.CreateFmt('Assembly %s not found', [AssemblyFileName]);

  GenericList := InspectedAssembly.GetCustomAttributesData;
  GenericItems := GenericList.AsGenericICollection;
  for c := 0 to GenericItems.Count - 1 do 
  begin
    s := GenericList.Item[c].ToString;
    Log(c.ToString + ': ' + s);
    if s.StartsWith('[System.Runtime.InteropServices.GuidAttribute("') then
      result := s.Substring(47, 36);
  end;
end;   

What I also don't understand, why doesn't _GenericIList provide a Length property? Is my trick via AsGenericICollection correct?


Solution

  • Only assemblies with ComVisible(true) are addressable by their GUID.

    I have changed the way the assembly is loaded. I load it now directly via TClrAssembly.LoadFrom instead of indirectly via RegisterDLLAssembly so I don't need to know the GUID anymore.

    In retrospect, this approach is much simpler and more direct.