Search path for a DLL referenced by a plug-in DLL

2019-05-10 11:47发布

I'm writing a Windows application plug-in (as a DLL) in native C++. Let's call it myplugin.dll. My plug-in references another DLL which we'll call other.dll.

My plug-in is installed in the myplugin subdirectory of the application's plugins directory:

application.exe
plugins\
    myplugin\
        myplugin.dll

myplugin.dll links implicitly to other.dll. I cannot delay-load other.dll because it exposes classes with virtual methods, and virtual method tables being considered as data, they cannot be imported from delay-loaded DLLs.

I would naturally like to place other.dll in the plugins\myplugin directory, next to myplugin.dll, but by default Windows will not look in plugins\myplugin when searching for other.dll (source).

What are my options here, other than placing other.dll in the root directory of the application?

(While the question Altering DLL search path for static linked DLL is related, it describes a scenario that doesn't quite make sense: an application implicitly linking against a plug-in DLL. I believe that a clear, typical scenario may help uncover additional solutions to this common issue, such as explicitly loading other.dll when myplugin.dll gets loaded by the application, if that would be possible.)

Edit: another similar question: Plugin DLLs that depend on other DLLs

Edit: I found a solution to the problem, see the accepted answer below. As far as I know, this is the cleanest solution. I hope it helps someone else.

1条回答
Lonely孤独者°
2楼-- · 2019-05-10 12:15

The idea I outlined in the last comment to my question turned out to be a good one.

I changed myplugin.dll to be a simple shim DLL. The entry point of that shim performs the following operations:

  1. It first loads other.dll (using LoadLibrary) from the directory containing the shim, plugins\myplugin\ in my case.
  2. It then loads myplugin-impl.dll, the "real" plug-in, from the same directory.

myplugin.dll then simply forward all calls to myplugin-impl.dll which does the actual job.

Note that myplugin-impl.dll still links implicitly to other.dll. However, when myplugin-impl.dll is loaded, other.dll has already been loaded by the shim in the address space of the application's process so no further loading occurs.

With this solution, we get the benefits of implicit DLL loading (in particular loading C++ classes with virtual methods) while still having full control on where the implicitly-loaded DLL is loaded from and how it is loaded.

查看更多
登录 后发表回答