Coffee on Mars
Coffee on Mars

Reputation: 998

Windows DLL unexpectedly loading more than once in the same application

A program I wrote (in C#) accesses through a C++/CLI wrapper library a native (c++) library I also wrote.

I noticed that the native library's DllMain method is called more than once, and the debugger thinks that multiple memory locations are connected to some of the library calls. From what I see, the library is initialized (and memory allocated) more than once.

Given that my code does not use functions such as LoadLibrary, and the dll is used including the library's .h files and .lib, why is it initialized more than once, and what can I do to avoid it?

Upvotes: 0

Views: 975

Answers (2)

valdo
valdo

Reputation: 12943

AFAIK DLL may not be loaded more than once into the same address space. Even if you call LoadLibrary explicitly the DLL won't be loaded more than once, instead its reference counter is incremented.

Also I don't understand exactly what you mean by "debugger thinks that multiple memory locations are connected to some of the library calls". A single imported symbol (function or a variable address) is filled by just one address during DLL binding.

I believe you have one of the following:

  • You may load simultaneously multiple versions of the same library (several DLL files). A typical error is to load debug and release DLL versions simultaneously.
  • Your DllMain is called several times, but it does not mean it's loaded several times. Do you check the parameters supplied to the DllMain? Is it DLL_PROCESS_ATTACH, or perhaps it's just DLL_THREAD_ATTACH/DLL_THREAD_DETACH?

Upvotes: 2

zdan
zdan

Reputation: 29450

A DLL's entry point is called when it is first loaded into the process, as well as when any thread in the process is started or stopped.

If this is causing problem's in your DLLMain, then you need to check the reason for DLL entry and handle appropriately.

Upvotes: 1

Related Questions