Search code examples
reflection64-bit32bit-64bitt4

Analyze 64-bit DLL from within T4 template in Visual Studio (32-bit) using Reflection


I would like to analyse a DLL from within a T4 template using Reflection, so that I can generate code based on the results of the reflection analysis. I know EnvDTE would be a better option, but this is not possible in my case for several reasons.

The problem with reflection is that the DLL is a 64-bit DLL and if I load that within the T4 template I get a BadImageFormatException because I am trying to load a 64-bit DLL into a 32-bit process (Visual Studio 2012).

Is there any way to analyse the contents of that DLL within T4, preferrably using reflection?

I have already thought about writing a console application which analyses the DLL, writes the results to an XML file which is then consumed by the T4 template, but that is not really my favorite solution...

BTW: The DLL is a managed C++ DLL. So Roslyn is no option either because it only supports C# and VB).


Solution

  • A thing worth testing is that if loading an assembly for reflection only works for you. I did experiment a bit and it seems it succeeds loading a 64bit assembly into a 32bit process then. It can't execute obviously but that should be ok for you if I understood you correctly:

    For the full sample look at: https://github.com/mrange/CodeStack/tree/master/q18985529/Reflect

    var assembly = Assembly.ReflectionOnlyLoad ("X64");
    
    var types = assembly.GetTypes ();
    
    foreach (var type in types)
    {
        Console.WriteLine (type.FullName);
    
        foreach (var field in type.GetFields ())
        {
            Console.WriteLine ("  {0} {1}", field.FieldType, field.Name);
        }
    
        foreach (var property in type.GetProperties ())
        {
            Console.WriteLine ("  {0} {1}", property.PropertyType, property.Name);
        }
    
    }
    

    Loading for ReflectionOnly has some drawbacks IIRC but sometimes it's worth it.