19

I have an external c++ dll to import using DLLImport. If my application is compiling in x64 I need to import the x64 version of this dll, if it is an x86 build, I need the x86 dll.

What is the best way to achieve this?

Ideally, I'd like some preprocessor directive, but I understand this doesn't work in c#?

More info: the DLL is being imported by a project which is set to AnyCPU. A parent project is the one which determines whether the application compiles as x64 or x86. We compile both versions for different customers - and I want to share the child project in both versions.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
Sugrue
  • 3,629
  • 5
  • 35
  • 53
  • 1
    What about to import BOTH versions (private methods) but to expose to client code the right one depending on environment? With .NET 4 just check [Environment.Is64BitOperatingSystem](http://msdn.microsoft.com/en-us/library/system.environment.is64bitoperatingsystem.aspx). Note I wouldn't keep two different versions of C# application because of dependant native DLL (so I wouldn't use preprocessor for this). – Adriano Repetti Aug 13 '12 at 12:54
  • Michael - that is nearly my question, but I have one extra complication which means their solution won't work. My dll is imported by a project which is anycpu, and a parent project decides if the application is x64 or x86 – Sugrue Aug 13 '12 at 12:57
  • 1
    @Sugrue Then you will need to use a runtime solution, namely import both and use `Environment.Is64BitProcess`, or `sizeof(void*)`, or `IntPtr.Size`. – Michael Graczyk Aug 13 '12 at 12:58
  • Possible duplicate of [Preprocessor directive in C# for importing based on platform](https://stackoverflow.com/questions/1313402/preprocessor-directive-in-c-sharp-for-importing-based-on-platform) – Cœur Jul 14 '18 at 14:13

2 Answers2

29

This is primarily a deployment problem, just have your installer copy the right DLL based on the Windows version on the target machine.

But nobody ever likes to do that. Dynamically pinvoking the correct DLL's function is enormously painfully, you have to write delegate types for every exported function and use LoadLibrary + GetProcAddress + Marshal.GetDelegateForFunctionPointer to create the delegate object.

But nobody ever likes to do that. The less painful tack is to declare the function twice, giving it different names and using the EntryPoint property in the [DllImport] attribute to specify the real name. Then test at runtime which you want to call.

But nobody ever likes to do that. The most effective trick is steer Windows into loading the correct DLL for you. First thing you have to do is copy the DLL into a directory where Windows will not look for it. Best way is to create an "x86" and an "x64" subdirectory in your build directory and copy the appropriate DLL into each. Do so by writing a post-build event that creates the directories and copies the DLLs.

Then tell Windows about it by pinvoking SetDllDirectory(). The path you specify will be added to the directories that Windows searches for a DLL. Like this:

using System;
using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;

class Program {
    static void Main(string[] args) {
        var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
        path = Path.Combine(path, IntPtr.Size == 8 ? "x64" : "x86");
        bool ok = SetDllDirectory(path);
        if (!ok) throw new System.ComponentModel.Win32Exception();
        //etc..
    }
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool SetDllDirectory(string path);
}

Do consider if having the code run in 64-bit mode is actually useful to you. It is pretty rare to need the giant virtual memory address space you get from it, the only real benefit. You still need to support the 32-bit version that needs to operate correctly in the 2 gigabyte case.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 1
    Personally I prefer an explicit call to `LoadLibrary` passing the full path, rather than modifying DLL search path which always feels clunky to me. The essential idea is the same of course. – David Heffernan Sep 12 '14 at 10:46
  • LoadLibrary is covered by the second paragraph. Bad idea. – Hans Passant Sep 12 '14 at 10:48
  • @HansPassant Not really: you can declare normal [DllImport("myLibrary.dll"] extern static void Method1(); and use LoadLibrary with a full path like LoadLibrary("c:\temp\amd64\myLibrary.dll"); before calling Method1() pinvoke, and windows will use the already loaded myLibrary.dll – wech Jun 17 '21 at 06:26
5

Add both the x86 and the x86_64 DLL imports with different names, then you can conditionally invoke them depending on the architecture at runtime by checking the value of Environment.Is64BitProcess (or IntPtr.size if you're using < .Net 4). This will work regardless of whether the project is built as x86, x86_64 or AnyCPU

Alternatively, set up 2 different build configurations - one that only does x86 and one that only does x86_64, give each one a conditional compilation symbol and use an #ifdef on your custom symbol.

PhonicUK
  • 13,486
  • 4
  • 43
  • 62
  • I think the OP does not know how to use `#ifdef` can you provide a quick code example for him, and perhaps a code example of loading the libraries too? Still gave a +1 without the examples though. – Scott Chamberlain Aug 13 '12 at 13:34