Search code examples
c++dllcom

How communicate between two DLLs loaded by same process without loading them again?


I want to communicate between two plug-ins in an application. Both plug-ins are C++ COM DLLs. Let's call them DLL1 and DLL2.

In DLL1, I have created an instance of a COM class that loads the COM DLL. From DLL2, I can create a similar instance of that COM class which may again load that COM DLL.

Basically, I don't want to load that COM DLL again from DLL2 and somehow get the handle of this COM DLL which is already loaded by DLL1. Can I call a function present in COM DLL(which is loaded by DLL1) from DLL2 without again loading it?

The constraint here is, I don't want to load COM DLL from DLL2. It will be loaded by DLL1 and I just want to execute that COM DLL function from DLL2.


Solution

  • From the LoadLibrary documentation:

    The system maintains a per-process reference count on all loaded modules. Calling LoadLibrary increments the reference count. Calling the FreeLibrary or FreeLibraryAndExitThread function decrements the reference count. The system unloads a module when its reference count reaches zero or when the process terminates (regardless of the reference count).

    and

    If the specified module is a DLL that is not already loaded for the calling process, the system calls the DLL's DllMain function with the DLL_PROCESS_ATTACH value. If DllMain returns TRUE, LoadLibrary returns a handle to the module. If DllMain returns FALSE, the system unloads the DLL from the process address space and LoadLibrary returns NULL.

    So calling LoadLibrary("XXX.dll") twice in the same process will only result loading the library once, the second call should get the same module handle back.