Matt Davis
Matt Davis

Reputation: 46052

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?

Upvotes: 4

Views: 4170

Answers (2)

Hans Passant
Hans Passant

Reputation: 942109

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.

Upvotes: 8

Timo Geusch
Timo Geusch

Reputation: 24351

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().

Upvotes: 3

Related Questions