Jimmy Pettersson
Jimmy Pettersson

Reputation: 464

C++ DLL fails to load on some machines

I'm trying to figure out the reason why my DLL fails to load on certain machines.

My application:

A C# program deployed with a setup.msi installer. Inside the installer are the DLLs that get placed in the install directory of the application. Ex:

OUTDIR = c:\Program Files\MyApplicationName\%OUTDIR%\MyApplication.exe
dir %OUTDIR%\DLL_FOLDER\\*.dll 

myDLL.dll

The C# application calls LoadLibrary specified by:

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr LoadLibrary(string libname);   

So basically

intPtr dll_handle = LoadLibrary("myDll.dll");

Is called and we use the dll_handle to call the desired functions.

So far this has worked on 5/7 of the machines I've deployed it on... What are the obvious mistakes I'm making here? :-)

Grateful for any help!

Upvotes: 0

Views: 1054

Answers (1)

David Heffernan
David Heffernan

Reputation: 612814

The most likely explanations are:

  1. The DLL cannot be found. Since you don't specify a full path, you rely on the Dynamic-Link Library Search Order to locate it. Placing the DLL in the same directory as the executable is the usual way to make sure you can find it, and find the right version.
  2. The DLL has non-matching bitness. For instance, your have a 64 bit process and a 32 bit DLL, or vice versa.
  3. The DLL is found, and has the right bitness, but the DLL's dependencies cannot be resolved. Usually this means that the appropriate MSVC runtime needs to be installed on the target machine.

The first diagnostics step to take is to check the return value of LoadLibrary and if it is NULL then call GetLastError to retrieve an error code. In p/invoke you do that like so:

IntPtr lib = LoadLibrary(...);
if (lib == IntPtr.Zero)
    throw new Win32Exception();

You can use a tool like Dependency Walker to debug the problem further.

Upvotes: 7

Related Questions