views:

58

answers:

2

I have a 32 bit .NET class library having a simple public class and a simple public method. I have a 64 bit .NET console application where using reflection, I wish to load the 32 bit assembly and consume its method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Host.TestLib;

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            var lib = Assembly.LoadFrom("Simple32bitAssembly.dll");
        }
    }
}

When I run this I get the following exception thrown:

System.BadImageFormatException was unhandled
Message=Could not load file or assembly 
'file:///E:\AjitTemp\c\32bit64Bit\ReflectionTest\test\bin\Debug\Simple32bitAssembly.dll' 
or one of its dependencies. An attempt was made to load a program with an incorrect format.

Googling suggests that I need to create a 64 bit wrapper for this 32 bit dll and load this wrapper using relection in my 64 bit console application? Is this the way? Any sample code would be very helpful.

+4  A: 

If you've specifically targeted both assemblies as 32bit and 64bit builds then you can't load a 32bit assembly into a 64 bit process (and vice versa).

If possible can you rebuild the 32bit assembly as 'Any CPU'? This would allow you to load 'Simple32bitAssembly' into the 64 bit console application.

With regard to your comment:

"There are business constraints where I cannot compile my 32 bit dll as 'Any CPU'."

The only way around this would be to deploy the 32 bit assembly into a separate 32 bit surrogate process. This process could expose functionality via .NET technologies such as:

    WCF
    Remoting
    ASP.NET Web Service

The disadvantages are that cross process calls can be expensive (although you could use named pipes in WCF or Remoting) and increasing the complexity of your application.

You'd also no longer have the ability to use reflection directly on this component from the consuming 64 application (but you could use reflection in the surrogate).

Such are the trials of mixed architecture applications.

Kev
there are business constraints where i cannot compile my 32 bit dll as 'Any CPU'.
Ajit Singh
@ajit - see my updated answer.
Kev
A: 

Use this clue : 64 bit C# with a 32 bit VB6 COM object

lsalamon