Jonathan D
Jonathan D

Reputation: 1364

How do I reference a 32 bit DLL in a 64 bit project?

I've got a C# 2.0 project which is set to target 'Any Cpu', however it is referencing a C++ project that's building a 32 bit dll.

When I try to run my program on a 64bit machine I get the following error:

System.BadImageFormatException was unhandled Message: Could not load file or assembly TreeTMHook, Version=1.0.2889.19619, Culture=neutral, PublicKeyToken=null or one of its dependencies. An attempt was made to load a program with an incorrect format.

How can I fix this?

Update

I want to be able to keep the main project as any cpu.

Thanks.

Upvotes: 16

Views: 11742

Answers (5)

Amol Shinde
Amol Shinde

Reputation: 1

Please use .net reflection and consume objects and its methods. Instead of direct 32 bit dll reference.

Upvotes: -2

JoeG
JoeG

Reputation: 13182

To keep you main project as Any Cpu, you need to supply both 32 and 64 bit version of the .dll - which should be possible, seeing as you're building it from source.

You then need to supply the executable with a manifest pointing it toward to right dll verion depending on platform.

Upvotes: 1

Bob
Bob

Reputation: 3351

You'll need to build your .NET project as 32bit (x86 target) if you want it to correctly load a 32-bit DLL on a 64bit machine.

RE: Update:

If you want to keep your project as "Any CPU", you'll need a 32bit and a 64bit version of the DLL, and make sure the appropriate version is distributed with your app. If you can't build the other project as 64bit, you must build your .NET project as 32-bit only.

Upvotes: 15

AndersK
AndersK

Reputation: 36082

You may want to take a look at this article it explains why it is not possible, in short since you are dealing with pointers when accessing unmanaged code.

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 941208

You will have to force your EXE project to run in 32-bit mode so it can use that C++ DLL. Project + Properties, Build tab, Platform Target = x86.

Upvotes: 4

Related Questions