Search code examples
.netdllc++-cli

Unmanaged DLL loading path


I have a managed c++/cli project that wraps an unmanaged dll.

I load the unmanaged dll with LoadLibrary, but the LoadLibrary call can't find my dll.

  HMODULE theDllHell = LoadLibrary(L"mylib.dll");

What do I have to do, so that my dll gets copied to the output directory and what path do I have to supply to LoadLibrary?


Solution

  • First: Assuming that you have the DLL added to the project, and it is visible inside the SolutionExplorer panel, just right-click on it and:

    • in BuildAction to "Content"
    • in CopyToOutputDir select 'CopyIfNewer'

    If I did not misremembered the options, it should be now copied to output dir whenever it is reasonable. Ref: File Properties on MSDN

    Second: The LoadLibrary searches a series of paths in a traditional Windows-specific order. The paths that you can be almost always sure are:

    • your current workind directory
    • the system DLL directories, like %windir%\system32

    Please check the docs: LoadLibraryA function there's for example 'SetDllDirectory' mentioned which you mind find very useful. Also, here's the search paths order explained in details: Dynamic-Link Library Search Order

    edit: of course you can just provide to the LoadLibrary the CWD-relative or full-absolute path to the file. That always solves the problem, but - I do not recommend it, as determinig the paths manually may be not a trivial task when the app is to be run on various versions and languages of the OS!