Thursday, January 13, 2005

Tackling mysterious crashing problems when calling run-time libraries from DLL modules within a C++ application

If your application has LoadLibrary() calls which hooks a DLL to your application, and you call a function within a DLL function which in turn calls C++ run-time library functions such as fopen() and fread(), the application may sometimes fail with an unhandled exception. Why?

This is probably because the linked run-time library with the application is different from the linked run-time library with the DLL module. For instance, if you specify your application to link to static run-time library, and then you specify your DLL module to link to dynamic run-time library, the application will crash when it attempts to call the function on the DLL module which access the run-time library, simply because they are referring to different libraries with completely separated code and memory management!

In order to fix this, during compilation, you must set both the application and the DLL module to use "Multi-threaded DLL (/MD)" run-time library. Do NOT use "Multi-threaded (/MT)" run-time library as it does not consider the case when the DLL is loaded dynamically by an application and thus would crash under such circumstances.

You may use "Multi-threaded Debug DLL (/MDd)" run-time library too, but again, you must make sure that both the application and DLL module are using the same "Multi-threaded Debug DLL (/MDd)" run-time library. Mixing and matching "Multi-threaded Debug DLL" and "Multi-threaded DLL" only gives you more headaches.

No comments: