Dynamically calling 32-bit or 64-bit DLL from c# application using Environment.Is64BitProcess
.net-4.0, c#
Solution
Lots of ways to do this:
this is a deployment problem, just get the right DLL copied by the installer, give them the same name
very few programs actually need the massive address space provided by 64-bit code. Just set the Platform target to x86
use the EntryPoint field of the [DllImport] attribute. Set it to "KFUNC". And give the methods different names. Now you can call one or the other, based on the value of IntPtr.Size
Demonstrating the last solution:
[DllImport("KEYDLL32.DLL", EntryPoint = "KFUNC")]
private static extern uint KFUNC32(int arg1, int arg2, int arg3, int arg4);
[DllImport("KEYDLL64.DLL", EntryPoint = "KFUNC")]
private static extern uint KFUNC64(int arg1, int arg2, int arg3, int arg4);
...
if (IntPtr.Size == 8) KFUNC64(1, 2, 3, 4);
else KFUNC32(1, 2, 3, 4);
Problem
I am working on a project written in C# for .NET 4.0 (via Visual Studio 2010). There is a 3rd party tool that requires the use of a C/C++ DLL and there are examples for 32-bit applications and 64-bit applications in C#. The problem is that the 32-bit demo statically links to the 32-bit DLL and the 64-bit demo statically links to the 64-bit DLL. Being a .NET application it could run as either a 32-bit or 64-bit process on the client PCs. The .NET 4.0 framework provides the Environment.Is64BitProcess property that returns true if the application is running as a 64-bit process. What I would like to do is to dynamically load the correct DLL after checking the Is64BitProcess property. However, when I research dynamically loading libraries I always come up with the following: ``` [DllImport("kernel32.dll")] public static extern IntPtr LoadLibrary(string dllToLoad); [DllImport("kernel32.dll")] public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName); [DllImport("kernel32.dll")] public static extern bool FreeLibrary(IntPtr hModule); ``` It would appear that these methods are specifically for the 32-bit operating system. Are there 64-bit equivalents? Would it cause problems to statically link both the 32-bit and 64-bit libraries as long as the appropriate methods are called based on the Is64BitProcess check? ``` public class key32 { [DllImport("KEYDLL32.DLL", CharSet = CharSet.Auto)] private static extern uint KFUNC(int arg1, int arg2, int arg3, int arg4); public static bool IsValid() { ... calls KFUNC() ... } } public class key64 { [DllImport("KEYDLL64.DLL", CharSet = CharSet.Auto)] private static extern uint KFUNC(int arg1, int arg2, int arg3, int arg4); public static bool IsValid() { ... calls KFUNC() ... } } ``` ... ``` if (Environment.Is64BitProcess) { Key64.IsValid(); } else { Key32.IsValid(); } ``` Thank you!!