Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AfxLoadLibrary vs. LoadLibrary

I have an MFC application that needs to load a DLL dynamically. The DLL will be used to retrieve a run-time value and then be unloaded. Do I need to create an MFC DLL and load it via AfxLoadLibrary() or can I create a traditional C++ dll and use the Win32 LoadLibrary() call? Does it matter?

like image 351
Matt Davis Avatar asked Dec 20 '22 12:12

Matt Davis


2 Answers

It is explicitly mentioned in the Remarks section of the MSDN Library article:

Be sure to use AfxLoadLibrary and AfxFreeLibrary (instead of the Win32 functions LoadLibrary and FreeLibrary) if your application uses multiple threads and if it dynamically loads an extension DLL. Using AfxLoadLibrary and AfxFreeLibrary insures that the startup and shutdown code that executes when the extension DLL is loaded and unloaded does not corrupt the global MFC state.

So if you are loading a DLL that contains MFC code or if you using threads in your program then you should use it.

That said, at least in modern versions of MFC, AfxLoadLibrary() doesn't do anything special:

HINSTANCE AFXAPI AfxLoadLibrary(LPCTSTR lpszModuleName)
{
     ASSERT(lpszModuleName != NULL);
     HINSTANCE hInstLib = LoadLibrary(lpszModuleName);
     return hInstLib;
}

So nothing is going to blow up badly if you guess wrong at this. Thank goodness.

like image 92
Hans Passant Avatar answered Dec 23 '22 02:12

Hans Passant


If you're creating a plain C++ DLL that doesn't make use of MFC at all, you don't need to create an MFC DLL and you should be able to use plain LoadLibrary().

like image 36
Timo Geusch Avatar answered Dec 23 '22 00:12

Timo Geusch