Share via


BadImageFormatException for a J# assembly on 64 Bit machine.

Hi,
Today I would like to write about something which left me clueless for hours and really made me work hard to figure the root cause.
I was building and running a suite on a 64 bit machine. This suite was written in C# and referring few existing dlls written in J#. I had ran same suite with same set of J# dlls referred on a 32 bit machine and everything used to work fine there, but suddenly on the 64 bit machine it stopped working.

It as compiling fine but while running, it was throwing following exception ...

System.BadImageFormatException
Message="Could not load file or assembly JSharp'ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format."

I had no clue that why suddenly it started failing on 64 bit machine while I didn't change anything, neither in my suite code nor in the referred J# assembly :(.
After spending no of hours I found out the reason. It was behaving erroneously only on 64 bit machine because J# compiler doesn't support 64 bit platform as of now. When one builds J# project, the exe or dll is always marked for 32 bit platform irrespective of the machine it is built on. That means even if I build a J# dll on 64 bit machine, it will be marked as 32 bit dll only.

So when I refer such a J# dll in C# project and build the C# project on 64 bit machine, C# dll is built for 'Any CPU' platform by default. On 64 bit machine 'Any CPU' maps to 64 bit platform. Now when I run such a C# project which has been built for 'Any CPU' platform and refers a J# dll, BadImageFormatException is thrown because loader tries to load a 32 bit dll in 64 bit process address apace which is obviously going to fail.

This issue is there not only for J#. You can build a C# or VB .net dll for a 32 bit platform by passing /platform : x86 switch to compiler. Now if you refer such a dll in a C# project, build it on 64 bit machine for 'Any CPU', run it then you will hit same exception. Solution to overcome this situation is that while building your C#/VB .net project on 64 bit, which refers 32 bit C#/J#/VB .net dll, you must specify /platform:x86 switch to compiler.

Since J# doesn't support 64 bit platform in VS 2005 (J# supports only 32 bit platform in VS 2005), this switch /platform : x86 is not there for J# compiler. If you try specifying it to J# compiler (vjc), it will crib saying invalid switch. J# compiler by default compiles for x86 only.

So friends, if you ever hit BadImageFormatException, do check the target platform of the assembly. You might also be running into the same problem.