views:

212

answers:

1

Hi,

I'm programing on C++, I'm using Visual Studio 2008, Windows XP, and I have the following problem: My application, that is a DLL that can be used from Python, loads an external dll, uses the required methods, and then unloads this external Dll. It's working properly, but after more than 1000 cycles the method "LoadLibraryA" returns a NULL reference.

The main steps are:

HINSTANCE h = NULL;
h = LoadLibraryA(dllfile.c_str());
DWORD dw = GetLastError(); 

The error got is:

ERROR_DLL_INIT_FAILED
1114 (0x45A) A dynamic link library (DLL) initialization routine failed.

The Dll is unloaded by using the following:

FreeLibrary(mDLL);
mDLL = NULL;

Where mDLL is defined like this:

HINSTANCE mDLL;

First alternative tried: Just load the Dll only once, and unloaded it when the application ends. This fix the problem but introduces a new one.

When the application ends, instead of first executing the DllMain method of my applicaion, wich unloads the external DLL, is executing first the DllMain method of the other Dll. This cause the following error because my application is trying to unload a Dll that was unload by itself previously.

"Unhandled exception at 0x04a00d07 (DllName.DLL) in Python.exe: 0xC0000005: Access violation reading location 0x0000006b".

Any suggestion will be welcomed. Thanks in advance. Regards.

A: 

Make sure that initialization code of the loaded/unloaded library doesn't leak memory. Many libraries expect to be loaded only once and not always clean up their resources properly.

E.g. in C++ file at the top level one can declare and initialize a variable like this:

AClass *a = new AClass(1,2,3);

The code would be executed when library is loaded automatically. Yet, now, it is impossible to free the hanging instance as library doesn't know precisely when/how it is going to be unloaded. In the case one can either replace "AClass *a" with "AClass a" or write your own DllMain for the library and free resources on DLL_PROCESS_DETACH.

If you have no control over the library's code, then it might make sense to create a cache of loaded libraries and simply never unload them. It is very hard to imagine that there would be unlimited number of libraries to overload such cache.

Dummy00001