# How do I call a 32-bit DLL using .NET/Link and a 64-bit version of Mathematica?

The .NET/Link tutorial shows how to call functions defined in DLLs. The example uses the GetTickCount Win32 API function

<< NetLink
InstallNET[]
getTickCount = DefineDLLFunction["GetTickCount", "kernel32.dll", "int", {}]

getTickCount[]

(* ==> 91226108 *)


Unfortunately this does not work by default when usign a 64-bit version of Mathematica to call a function defined in a 32-bit DLL. Let's use the 32-bit version of kernel32.dll to test:

getTickCount =
DefineDLLFunction["GetTickCount", "c:\\windows\\SysWOW64\\kernel32.dll", "int", {}]

getTickCount[]

NET::netexcptn: A .NET exception occurred: System.BadImageFormatException:
An attempt was made to load a program with an incorrect format.
(Exception from HRESULT: 0x8007000B)


How can I call a 32-bit DLL from a 64-bit Mathematica?

-
I thought this will be valuable for the community. It's based on a MathGroup question I solved. –  Szabolcs Mar 2 '12 at 10:13

The solution is forcing .NET/Link to load its 32-bit executable instead of the 64-bit one. Since Mathematica communicated with the .NET/Link process through MathLink, it does not matter if the Mathematica kernel is 64 bit and the .NET/Link executable is a 32 bit version. They are separate processes. However, the .NET/Link executable must match the DLL that is being loaded.

There is an undocumented option to force loading the 32-bit version of .NET/Link:

UninstallNET[]
InstallNET["Force32Bit" -> True]


Now 32-bit DLLs can be loaded through .NET/Link, but 64-bit ones cannot.

-

Or simply use

ReinstallNET["Force32Bit" -> True]


which is a convenience function that calls

UninstallNET[]
InstallNET["Force32Bit" -> True]

-
I indeed learned ReinstallNET["Force32Bit"->True]` in Integrating C and Mathematica by Joel F. Klein and Todd Gayley –  unstable May 18 '12 at 8:54