DLL FAQ
1. What is the difference between static link library and dynamic link library?
Static libraries are linked at compile time. Dynamic
libraries are linked at runtime.
static library is faster than dynamic library.

2. How to use opencv library in visual C++?
Include lib file
Project - Properties - Configuration Properties - Linker - Input - Additional Dependencies,
Add line
#include "libfile.h" 

 
3. What is Dynamic link library?
A dynamic-link library (DLL) is an executable file that acts as a shared library of functions. Dynamic linking provides a way for a process to call a function that is not part of its executable code. The executable code for the function is located in a DLL, which contains one or more functions that are compiled, linked, and stored separately from the processes that use them. DLLs also facilitate the sharing of data and resources. Multiple applications can simultaneously access the contents of a single copy of a DLL in memory.

Dynamic linking differs from static linking in that it allows an executable module (either a .dll or .exe file) to include only the information needed at run time to locate the executable code for a DLL function. In static linking, the linker gets all of the referenced functions from the static link library and places it with your code into your executable.

Using dynamic linking instead of static linking offers several advantages. DLLs save memory, reduce swapping, save disk space, upgrade easier, provide after-market support, provide a mechanism to extend the MFC library classes, support multilanguage programs, and ease the creation of international versions.

 
4. How to create a new dynamic link library (DLL) project?
1. From the File menu, select New and then Project….
2. From the Project types pane, under Visual C++, select Win32.
3. From the Templates pane, select Win32 Console Application.
4. Choose a name for the project, such as MathFuncsDll, and enter it in the Name field. Choose a name for the solution, such as DynamicLibrary, and enter it in the Solution Name field.
5. Press OK to start the Win32 application wizard. From the Overview page of the Win32 Application Wizard dialog, press Next.
6. From the Application Settings page of the Win32 Application Wizard, under Application type, select DLL if it is available or Console application if DLL is not available. Some versions of            Visual Studio do not support creating a DLL project using wizards. You can change this later to make your project compile into a DLL.
7. From the Application Settings page of the Win32 Application Wizard, under Additional options, select Empty project.
8. Press Finish to create the project.

 
5. How to add a class to the dynamic link library?
To create a header file for a new class, from the Project menu, select Add New Item…. The Add New Item dialog will be displayed. From the Categories pane, under Visual C++, select Code. From the Templates pane, select Header File (.h). Choose a name for the header file, such as MathFuncsDll.h, and press Add. A blank file will be displayed.
# Add a simple class named MyMathFuncs to do common mathematical operations, such as addition, subtraction, multiplication, and division. The code should resemble the following:


// MathFuncsDll.h

namespace MathFuncs
{
class MyMathFuncs
{
public:
// Returns a + b
static __declspec(dllexport) double Add(double a, double b);

// Returns a - b
static __declspec(dllexport) double Subtract(double a, double b);

// Returns a * b
static __declspec(dllexport) double Multiply(double a, double b);

// Returns a / b
// Throws DivideByZeroException if b is 0
static __declspec(dllexport) double Divide(double a, double b);
};
}

#


To create a source file for a new class, from the Project menu, select Add New Item…. The Add New Item dialog will be displayed. From the Categories pane, under Visual C++, select Code. From the Templates pane, select C++ File (.cpp). Choose a name for the source file, such as MathFuncsDll.cpp, and press Add. A blank file will be displayed.
#

Implement the functionality for MyMathFuncs in the source file. The code should resemble the following:

// MathFuncsDll.cpp
// compile with: /EHsc /LD

#include "MathFuncsDll.h"

#include <stdexcept>

using namespace std;

namespace MathFuncs
{
double MyMathFuncs::Add(double a, double b)
{
return a + b;
}

double MyMathFuncs::Subtract(double a, double b)
{
return a - b;
}

double MyMathFuncs::Multiply(double a, double b)
{
return a * b;
}

double MyMathFuncs::Divide(double a, double b)
{
if (b == 0)
{
throw new invalid_argument("b cannot be zero!");
}

return a / b;
}
}

#

To build the project into a DLL, from the Project menu, select MathFuncsDll Properties…. From the left pane, under Configuration Properties, select General. From the right pane, change the Configuration Type to Dynamic Library (.dll). Press OK to save the changes.

Compile the dynamic link library by selecting Build Solution from the Build menu. This creates a DLL that can be used by other programs. For more information on DLLs, see DLLs.

 
6. How to create an application that references the dynamic link library?
1. To create an application that will reference and use the dynamic link library that was just created, from the File menu, select New and then Project….
2. From the Project types pane, under Visual C++, select Win32.
3. From the Templates pane, select Win32 Console Application.
4. Choose a name for the project, such as MyExecRefsDll, and enter it in the Name field. Next to Solution, select Add to Solution from the drop down list. This will add the new project to the        same solution as the dynamic link library.
5. Press OK to start the Win32 Application Wizard. From the Overview page of the Win32 Application Wizard dialog, press Next.
6. From the Application Settings page of the Win32 Application Wizard, under Application type, select Console application.
7. From the Application Settings page of the Win32 Application Wizard, under Additional options, deselect Precompiled header.
8. Press Finish to create the project.

7. How to use the functionality from the class library in the console application?
# After you create a new Console Application, an empty program is created for you. The name for the source file will be the same as the name you chose for the project above. In this example, it is named MyExecRefsDll.cpp.
# To use the math routines that were created in the dynamic link library, you must reference it. To do this, select References… from the Project menu. From the Property Pages dialog, expand the Common Properties node and select References. Then select the Add New Reference… button.
# The Add Reference dialog is displayed. This dialog lists all the libraries that you can reference. The Project tab lists all the projects in the current solution and any libraries they contain. From the Projects tab, select MathFuncsDll. Then select OK. For more information on the Add Reference dialog
# To reference the header files of the dynamic link library, you must modify the include directories path. To do this, from the Property Pages dialog, expand the Configuration Properties node, then the C/C++ node, and select General. Next to Additional Include Directories, type in the path to the location of the MathFuncsDll.h header file.
# Dynamic link libraries are not loaded by the executable until runtime. You must tell the system where to locate MathFuncsDll.dll. This is done using the PATH environment variable. To do this, from the Property Pages dialog, expand the Configuration Properties node and select Debugging. Next to Environment, type in the following: PATH=<path to MathFuncsDll.dll file>, where <path to MathFuncsDll.dll file> is replaced with the actual location of MathFuncsDll.dll. Press OK to save all the changes made.
# You can now use the MyMathFuncs class in this application. Replace the contents of MyExecRefsDll.cpp with the following code:


// MyExecRefsDll.cpp
// compile with: /EHsc /link MathFuncsDll.lib

#include <iostream>
#include "MathFuncsDll.h"
using namespace std;
int main()
{
double a = 7.4;
int b = 99;
cout << "a + b = " <<
MathFuncs::MyMathFuncs::Add(a, b) << endl;
cout << "a - b = " <<
MathFuncs::MyMathFuncs::Subtract(a, b) << endl;
cout << "a * b = " <<
MathFuncs::MyMathFuncs::Multiply(a, b) << endl;
cout << "a / b = " <<
MathFuncs::MyMathFuncs::Divide(a, b) << endl;
return 0;
}

# Build the executable by selecting Build Solution from the Build menu.


 
8. How to run the dll application?
# Make sure MyExecRefsDll is selected as the default project. From the Solution Explorer, select MyExecRefsDll, and then select Set As StartUp Project from the Project menu.
# To run the project, select Start Without Debugging from the Debug menu.

 
9. How to Export calls from a DLL ?
A DLL file has a layout very similar to an .exe file, with one important difference — a DLL file contains an exports table. The exports table contains the name of every function that the DLL exports to other executables. These functions are the entry points into the DLL; only the functions in the exports table can be accessed by other executables. Any other functions in the DLL are private to the DLL. The exports table of a DLL can be viewed by using the DUMPBIN tool with the /EXPORTS option.

You can export functions from a DLL using two methods:

* Create a module definition (.def) file and use the .def file when building the DLL. Use this approach if you want to export functions from your DLL by ordinal rather than by name.
* Use the keyword __declspec(dllexport) in the function's definition.
When exporting functions with either method, make sure to use the __stdcall calling convention.

 
10. Explain DUMPBIN Reference?
The Microsoft COFF Binary File Dumper (DUMPBIN.EXE) displays information about Common Object File Format (COFF) binary files. You can use DUMPBIN to examine COFF object files, standard libraries of COFF objects, executable files, and dynamic-link libraries (DLLs). 

 
11. How to Initialize a DLL ?
Typically, your DLL has initialization code (such as allocating memory) that must execute when your DLL loads. When using Visual C++, where you add code to initialize your DLL depends on the type of DLL you are building. If you do not need to add initialization or termination code, there is nothing special you have to do when building your DLL. If you need to initialize your DLL, the following table describes where to add your code.
In Win32, all DLLs might contain an optional entry-point function (usually called DllMain) that is called for both initialization and termination. This gives you an opportunity to allocate or release additional resources as needed. Windows calls the entry-point function in four situations: process attach, process detach, thread attach, and thread detach.
The C run-time library provides an entry-point function called _DllMainCRTStartup, and it calls DllMain. Depending on the type of DLL, you should have a function called DllMain in your source code or you should use the DllMain provided in the MFC library.

12. What is a Regular DLL ?
Because regular DLLs have a CWinApp object, they should perform their initialization and termination tasks in the same location as an MFC application: in the InitInstance and ExitInstance member functions of the DLL's CWinApp-derived class. Because MFC provides a DllMain function that is called by _DllMainCRTStartup for PROCESS_ATTACH and PROCESS_DETACH, you should not write your own DllMain function. The MFC-provided DllMain function calls InitInstance when your DLL is loaded and it calls ExitInstance before the DLL is unloaded.

A regular DLL can keep track of multiple threads by calling TlsAlloc and TlsGetValue in its InitInstance function. These functions allow the DLL to track thread-specific data.

In your regular DLL that dynamically links to MFC, if you are using any MFC OLE, MFC Database (or DAO), or MFC Sockets support, respectively, the MFC debug extension DLLs MFCOxxD.dll, MFCDxxD.dll, and MFCNxxD.dll (where xx is the version number) are linked in automatically. You must call one of the following predefined initialization functions for each of these DLLs that you are using in your regular DLL's CWinApp::InitInstance.

Type of MFC support                              Initialization function to call

MFC OLE (MFCOxxD.dll)                          AfxOleInitModule
MFC Database (MFCDxxD.dll)                   AfxDbInitModule
MFC Sockets (MFCNxxD.dll)                     AfxNetInitModule

 
13. How to Initialize Extension DLLs ?
extension DLLs do not have a CWinApp-derived object (as do regular DLLs), you should add your initialization and termination code to the DllMain function that the MFC DLL Wizard generates.

 
14. How to Initialize Non-MFC DLLs ?
To initialize non-MFC DLLs, your DLL source code must contain a function called DllMain.

 
15. What is Run-Time Library Behavior ?
The C/C++ run-time library code performs the DLL startup sequence, eliminating the need to link with a separate module as was necessary in Windows 3.x. Included in the C/C++ run-time library code is the DLL entry-point function called _DllMainCRTStartup. The _DllMainCRTStartup function does several things, including calling _CRT_INIT, which initializes the C/C++ run-time library and invokes C++ constructors on static, non-local variables. Without this function, the run-time library would be left in an uninitialized state. _CRT_INIT is available for both a statically linked CRT or linking to the CRT DLL Msvcrt.dll, from a user DLL.

While it is possible to specify another entry-point function using the /ENTRY: linker option, it is not recommended because your entry-point function would have to duplicate everything that _DllMainCRTStartup does. When building DLLs in Visual C++, _DllMainCRTStartup is linked in automatically and you do not need to specify an entry-point function using the /ENTRY: linker option.

In addition to initializing the C run-time library, _DllMainCRTStartup calls a function called DllMain. Depending on the kind of DLL you are building, Visual C++ provides DllMain for you and it gets linked in so that _DllMainCRTStartup always has something to call. In this way, if you do not need to initialize your DLL, there is nothing special you have to do when building your DLL. If you need to initialize your DLL, where you add your code depends on the kind of DLL you are writing.

 
16. How to Link an Executable to a DLL ?
An executable file links to (or loads) a DLL in one of two ways:

* Implicit linking
* Explicit linking

Implicit linking is sometimes referred to as static load or load-time dynamic linking. Explicit linking is sometimes referred to as dynamic load or run-time dynamic linking.

With implicit linking, the executable using the DLL links to an import library (.lib file) provided by the maker of the DLL. The operating system loads the DLL when the executable using it is loaded. The client executable calls the DLL's exported functions just as if the functions were contained within the executable.
With explicit linking, the executable using the DLL must make function calls to explicitly load and unload the DLL and to access the DLL's exported functions. The client executable must call the exported functions through a function pointer.
An executable can use the same DLL with either linking method. Furthermore, these mechanisms are not mutually exclusive, as one executable can implicitly link to a DLL and another can attach to it explicitly.

17. What is Implicit linking?
To implicitly link to a DLL, executables must obtain the following from the provider of the DLL:

* A header file (.h file) containing the declarations of the exported functions and/or C++ classes. The classes, functions, and data should all have __declspec(dllimport), for more information, see dllexport, dllimport.
* An import library (.LIB files) to link with. (The linker creates the import library when the DLL is built.)
* The actual DLL (.dll file).
Executables using the DLL must include the header file containing the exported functions (or C++ classes) in each source file that contains calls to the exported functions. From a coding perspective, the function calls to the exported functions are just like any other function call.
To build the calling executable file, you must link with the import library. If you are using an external makefile, specify the file name of the import library where you list other object (.obj) files or libraries that you are linking with.
The operating system must be able to locate the DLL file when it loads the calling executable.

 
18. What is Explicit linking?
With explicit linking, applications must make a function call to explicitly load the DLL at run time. To explicitly link to a DLL, an application must:

* Call LoadLibrary (or a similar function) to load the DLL and obtain a module handle.
* Call GetProcAddress to obtain a function pointer to each exported function that the application wants to call. Because applications are calling the DLL's functions through a pointer, the compiler    does not generate external references, so there is no need to link with an import library.
* Call FreeLibrary when done with the DLL.

 
19. Explain LoadLibrary and AfxLoadLibrary?
Processes call LoadLibrary (or AfxLoadLibrary) to explicitly link to a DLL. If successful, the function maps the specified DLL into the address space of the calling process and returns a handle to the DLL that can be used with other functions used in explicit linking such as GetProcAddress and FreeLibrary.

LoadLibrary attempts to locate the DLL using the same search sequence used for implicit linking. If the system cannot find the DLL or if the entry-point function returns FALSE, LoadLibrary returns NULL. If the call to LoadLibrary specifies a DLL module already mapped into the address space of the calling process, the function simply returns a handle of the DLL and increments the module's reference count.

If the DLL has an entry-point function, the operating system calls the function in the context of the thread that called LoadLibrary. The entry-point function is not called if the DLL is already attached to the process because of a previous call to LoadLibrary with no corresponding call to the FreeLibrary function.

MFC applications loading extension DLLs should use AfxLoadLibrary instead of LoadLibrary. AfxLoadLibrary handles thread synchronization before calling LoadLibrary. The interface (function prototype) to AfxLoadLibrary is the same as LoadLibrary.

 
20. What are the Advantages of Using DLLs ?
Dynamic linking has the following advantages:

* Saves memory and reduces swapping. Many processes can use a single DLL simultaneously, sharing a single copy of the DLL in memory. In contrast, Windows must load a copy of the library code into memory for each application that is built with a static link library.
* Saves disk space. Many applications can share a single copy of the DLL on disk. In contrast, each application built with a static link library has the library code linked into its executable image as a separate copy.
* Upgrades to the DLL are easier. When the functions in a DLL change, the applications that use them do not need to be recompiled or relinked as long as the function arguments and return values do not change. In contrast, statically linked object code requires that the application be relinked when the functions change.
* Provides after-market support. For example, a display driver DLL can be modified to support a display that was not available when the application was shipped.
* Supports multilanguage programs. Programs written in different programming languages can call the same DLL function as long as the programs follow the function's calling convention. The programs and the DLL function must be compatible in the following ways: the order in which the function expects its arguments to be pushed onto the stack, whether the function or the application is responsible for cleaning up the stack, and whether any arguments are passed in registers.
* Provides a mechanism to extend the MFC library classes. You can derive classes from the existing MFC classes and place them in an MFC extension DLL for use by MFC applications.
* Eases the creation of international versions. By placing resources in a DLL, it is much easier to create international versions of an application. You can place the strings for each language version of your application in a separate resource DLL and have the different language versions load the appropriate resources.
If for some reason Windows cannot load the DLL, the process can attempt to recover from the error. For example, the process could notify the user of the error and have the user specify another path to the DLL. 

 
21. What is Non-MFC DLLs?
A non-MFC DLL is a DLL that does not use MFC internally, and the exported functions in the DLL can be called by either MFC or non-MFC executable files. Functions are usually exported from a non-MFC DLL using the standard C interface.

22. What are the features of a regular DLL, statically linked to MFC?
* The client executable can be written in any language that supports the use of DLLs (C, C++, Pascal, Visual Basic, and so on); it does not have to be an MFC application.
* The DLL can link to the same MFC static link libraries used by applications. There is no longer a separate version of the static link libraries for DLLs.
* Before version 4.0 of MFC, USRDLLs provided the same type of functionality as regular DLLs statically linked to MFC. As of Visual C++ version 4.0, the term USRDLL is obsolete.

 
23. What are the requirement needed for a regular DLL, statically linked to MFC?
* This type of DLL must instantiate a class derived from CWinApp.
* This type of DLL uses the DllMain provided by MFC. Place all DLL-specific initialization code in the InitInstance member function and termination code in ExitInstance as in a normal MFC         application.
* Even though the term USRDLL is obsolete, you must still define "_USRDLL" on the compiler command line. This definition determines which declarations is pulled in from the MFC header files.

 
24. What are the features of a regular DLL, dynamically linked to MFC?
* This is a new type of DLL introduced by Visual C++ 4.0.
* The client executable can be written in any language that supports the use of DLLs (C, C++, Pascal, Visual Basic, and so on); it does not have to be an MFC application.
* Unlike the statically linked regular DLL, this type of DLL is dynamically linked to the MFC DLL (also known as the shared MFC DLL).
* The MFC import library linked to this type of DLL is the same one used for extension DLLs or applications using the MFC DLL: MFCxx(D).lib.

 
25. What are the requirement needed for a regular DLL, dynamically linked to MFC?
* These DLLs are compiled with _AFXDLL defined, just like an executable that is dynamically linked to the MFC DLL. But _USRDLL is also defined, just like a regular DLL that is statically            linked to MFC.
* This type of DLL must instantiate a CWinApp-derived class.
* This type of DLL uses the DllMain provided by MFC. Place all DLL-specific initialization code in the InitInstance member function and termination code in ExitInstance as in a normal MFC application.

 
26. How to Use Database, OLE, and Sockets Extension DLLs in Regular DLLs ?
When using an extension DLL from a regular DLL, if the extension DLL is not wired into the CDynLinkLibrary object chain of the regular DLL, you might run into one or more of a set of related problems. Because the debug versions of the MFC Database, OLE, and Sockets support DLLs are implemented as extension DLLs, you might see similar problems if you are using these MFC features, even if you are not explicitly using any of your own extension DLLs. Some symptoms are:

* When attempting to deserialize an object of a type of class defined in the extension DLL, the message "Warning: Cannot load CYourClass from archive. Class not defined." appears in the TRACE debug window and the object fails to serialize.
* An exception indicating bad class might be thrown.
* Resources stored in the extension DLL fail to load because AfxFindResourceHandle returns NULL or an incorrect resource handle.
* DllGetClassObject, DllCanUnloadNow, and the UpdateRegistry, Revoke, RevokeAll, and RegisterAll member functions of COleObjectFactory fail to locate a class factory defined in the extension DLL.
* AfxDoForAllClasses does not work for any classes in the extension DLL.
* Standard MFC database, sockets, or OLE resources fail to load. For example, AfxLoadString(AFX_IDP_SQL_CONNECT_FAIL) returns an empty string, even when the regular DLL is properly using the MFC Database classes.
The solution to these problems is to create and export an initialization function in the extension DLL that creates a CDynLinkLibrary object. Call this initialization function exactly once from each regular DLL that uses the extension DLL

27. What is CDynLinkLibrary Objects?
During each of the operations mentioned at the beginning of this topic, MFC needs to search for a desired value or object. For example, during deserialization, MFC needs to search through all the currently available run-time classes to match objects in the archive with their proper run-time class.
As a part of these searches, MFC scans through all the extension DLLs in use by walking a chain of CDynLinkLibrary objects. CDynLinkLibrary objects attach automatically to a chain during their construction and are created by each extension DLL in turn during initialization. In addition, every module (application or regular DLL) has its own chain of CDynLinkLibrary objects.
For an extension DLL to get wired into a CDynLinkLibrary chain, it must create a CDynLinkLibrary object in the context of every module that uses the extension DLL. Therefore, if an extension DLL is going to be used from regular DLLs, it must provide an exported initialization function that creates a CDynLinkLibrary object. Every regular DLL that uses the extension DLL must call the exported initialization function.
If an extension DLL is only going to be used from an MFC application (.exe) and never from a regular DLL, then it is sufficient to create the CDynLinkLibrary object in the extension DLL's DllMain. This is what the MFC DLL Wizard extension DLL code does. When loading an extension DLL implicitly, DllMain loads and executes before the application ever starts. Any CDynLinkLibrary creations are wired into a default chain that the MFC DLL reserves for an MFC application.

 
28. How to Write an MFC Extension DLL?
An MFC Extension DLL is a DLL containing classes and functions written to embellish the functionality of the MFC classes. An MFC Extension DLL uses the shared MFC DLLs in the same way an application uses it, with a few additional considerations:

* The build process is similar to building an application that uses the shared MFC libraries with a few additional compiler and linker options.
* An MFC Extension DLL does not have a CWinApp-derived class.
* An MFC Extension DLL must provide a special DllMain. AppWizard supplies a DllMain function that you can modify.
* An MFC Extension DLL will usually provide an initialization routine to create a CDynLinkLibrary if the extension DLL wishes to export CRuntimeClasses or resources to the application. A derived class of CDynLinkLibrary may be used if per-application data must be maintained by the extension DLL.

These considerations are described in more detail below. You should also refer to the MFC Advanced Concepts sample DLLHUSK since it illustrates:

* Building an application using the shared libraries. (DLLHUSK.EXE is an MFC application that dynamically links to the MFC libraries as well as other DLLs.)
* Building an MFC Extension DLL. (Note the special flags such as _AFXEXT that are used in building an extension DLL)
* Two examples of MFC Extension DLLs. One shows the basic structure of an MFC Extension DLL with limited exports (TESTDLL1) and the other shows exporting an entire class interface (TESTDLL2).

Both the client application and any extension DLLs must use the same version of MFCxx.DLL. You should follow the convention of MFC DLL and provide both a debug and retail (/release) version of your extension DLL. This permits client programs to build both debug and retail versions of their applications and link them with the appropriate debug or retail version of all DLLs. 

 
29. How to Build an Extension DLL?
You can use AppWizard to create an MFC extension DLL project, and it will automatically generate the appropriate compiler and linker settings. It was also generate a DllMain function that you can modify.
If you are converting an existing project to an MFC extension DLL, start with the standard rules for building an application using the shared version of MFC, then do the following:

* Add /D_AFXEXT to the compiler flags. On the Project Properties dialog, select the C/C++ node. Then select the Preprocessor category. Add _AFXEXT to the Define Macros field, separating each of the items with semicolons.
* Remove the /Gy compiler switch. On the Project Properties dialog, select the C/C++ node. Then select the Code Generation category. Ensure that the "Enable Function-Level Linking" option is not enabled. This will make it easier to export classes because the linker will not remove unreferenced functions. If the original project is used to build a Regular DLL statically linked to MFC, change the /MT[d] compiler option to /MD[d].
* Build an export library with the /DLL option to LINK. This will be set when you create a new target, specifying Win32 Dynamic-Link Library as the target type.

 
30. What is Extension DLLs?
An MFC extension DLL is a DLL that typically implements reusable classes derived from existing Microsoft Foundation Class Library classes. Extension DLLs are built using the dynamic-link library version of MFC (also known as the shared version of MFC). Only MFC executables (either applications or regular DLLs) that are built with the shared version of MFC can use an extension DLL. With an extension DLL, you can derive new custom classes from MFC and then offer this extended version of MFC to applications that call your DLL.

Extension DLLs can also be used for passing MFC-derived objects between the application and the DLL. The member functions associated with the passed object exist in the module where the object was created. Because these functions are properly exported when using the shared DLL version of MFC, you can freely pass MFC or MFC-derived object pointers between an application and the extension DLLs it loads.

 
31. What are the different kinds of DLLs?
Using Visual C++, you can build Win32 DLLs in C or C++ that do not use the Microsoft Foundation Class (MFC) library. You can create a non-MFC DLL project with the Win32 Application Wizard.
The MFC library itself is available, in either static link libraries or in a number of DLLs, with the MFC DLL Wizard. If your DLL is using MFC, Visual C++ supports three different DLL development scenarios:

* Building a regular DLL that statically links MFC
* Building a regular DLL that dynamically links MFC
* Building an MFC extension DLL, which always dynamically link MFC

32. How yo Decide Which Kind of DLL to Use?
If your DLL does not use MFC, use Visual C++ to build a non-MFC Win32 DLL. Linking your DLL to MFC (either statically or dynamically) takes up significant disk space and memory. You should not link to MFC unless your DLL actually uses MFC.

If your DLL will be using MFC, and will be used by either MFC or non-MFC applications, you must build either a regular DLL that dynamically links to MFC or a regular DLL that statically links to MFC. In most cases, you probably want to use a regular DLL that dynamically links to MFC because the file size of the DLL will be much smaller and the savings in memory from using the shared version of MFC can be significant. If you statically link to MFC, the file size of your DLL will be larger and potentially take up extra memory because it loads its own private copy of the MFC library code.

Building a DLL that dynamically links to MFC is faster than building a DLL that statically links to MFC because it is not necessary to link MFC itself. This is especially true in debug builds where the linker must compact the debug information. By linking with a DLL that already contains the debug information, there is less debug information to compact within your DLL.

One disadvantage to dynamically linking to MFC is that you must distribute the shared DLLs Mfcx0.dll and Msvcrt.dll (or similar files) with your DLL. The MFC DLLs are freely redistributable, but you still must install the DLLs in your setup program. In addition, you must ship the Msvcrt.dll, which contains the C run-time library that is used both by your program and the MFC DLLs themselves.

If your DLL will only be used by MFC executables, you have a choice between building a regular DLL or an extension DLL. If your DLL implements reusable classes derived from the existing MFC classes or you need to pass MFC-derived objects between the application and the DLL, you must build an extension DLL.

If your DLL dynamically links to MFC, the MFC DLLs might be redistributed with your DLL. This architecture is particularly useful for sharing the class library between multiple executable files to save disk space and minimize memory usage.

Prior to version 4.0, Visual C++ only supported two kinds of DLLs that used MFC: USRDLLs and AFXDLLs. Regular DLLs statically linked to MFC have the same characteristics as the former USRDLL. MFC extension DLLs have the same characteristics as the former AFXDLLs.

 
33. Differences Between Win16 and Win32 DLLs?
If you have built 16-bit DLLs for Windows 3.x, you should find that building 32-bit DLLs is more convenient. The compiler offers more direct support, which can save you several steps in DLL creation. The specific differences between Win16 and Win32 DLLs are:

* There is no separate startup module that you have to link with. The DLL startup sequence is handled directly by C/C++ run-time library code linked into your DLL.
* The run-time library code initializes any static non-local C++ objects by calling the appropriate constructors. Each process gets its own copy of all the DLL's static data, including objects.
* You no longer need the function LibMain or a WEP (Windows Exit Procedure). Where you add initialization and termination code for your DLL depends on the type of DLL you are building. Instead of LibMain, you provide DllMain, which is called for both for both entry and exit.
* You can import and export symbols directly in your source code. If you use the __declspec(dllexport) attribute (similar to __export in Windows 3.x), you do not need to use a separate module-definition file for exports.
* Executables that use __declspec(dllimport) to import data, objects, and functions from a DLL cause the compiler to generate more efficient code.
* The timing of calls to routines registered with atexit can differ.
* In addition to Win32 non-MFC DLLs, Visual C++ offers three kinds of MFC DLLs.

 
34. Can a multithreaded application access an MFC DLL in different threads? 
Multithreaded applications can access regular DLLs that dynamically link to MFC and extension DLLs from different threads. And as of Visual C++ version 4.2, an application can access regular DLLs that statically link to MFC from multiple threads created in the application.

Prior to version 4.2, only one external thread could attach to a regular DLL that statically linked to MFC. For more information about restrictions accessing regular DLLs that statically link to MFC from multiple threads (prior to Visual C++ version 4.2), see the Knowledge Base article, "Multiple Threads and MFC _USRDLLs" (Q122676).

 
35. Can an MFC DLL create multiple threads?
Except during initialization, an MFC DLL can safely create multiple threads as long as it uses the Win32 thread local storage (TLS) functions such as TlsAlloc to allocate thread local storage. However, if an MFC DLL uses __declspec(thread) to allocate thread local storage, the client application must be implicitly linked to the DLL. If the client application explicitly links to the DLL, the call to LoadLibrary will not successfully load the DLL

 
36. Are there any MFC classes or functions that cannot be used in an MFC DLL? 
Extension DLLs use the CWinApp-derived class of the client application. They must not have their own CWinApp-derived class.
Regular DLLs must have a CWinApp-derived class and a single object of that application class, as does an MFC application. Unlike the CWinApp object of an application, the CWinApp object of the DLL does not have a main message pump.

Note that because the CWinApp::Run mechanism does not apply to a DLL, the application owns the main message pump. If the DLL opens modeless dialog boxes or has a main frame window of its own, the application's main message pump must call a routine exported by the DLL, which in turn calls the CWinApp::PreTranslateMessage member function of the DLL's application object.

37. How do I debug my DLL? 
To debug a DLL using Visual C++, you must build a debugging version of the DLL and call it from an application. However, it is not necessary to build the debugging version of the calling application or to build the calling application with Visual C++.

 
38. What optimization techniques should I use to improve the client application's performance when loading? 
If your DLL is a regular DLL that is statically linked to MFC, changing it to a regular DLL that is dynamically linked to MFC reduces the file size.

If the DLL has a large number of exported functions, use a .def file to export the functions (instead of using __declspec(dllexport)) and use the .def file NONAME attribute on each exported function. The NONAME attribute causes only the ordinal value and not the function name to be stored in the DLL's export table, which reduces the file size.

DLLs that are implicitly linked to an application are loaded when the application loads. To improve the performance when loading, try dividing the DLL into different DLLs. Put all the functions that the calling application needs immediately after loading into one DLL and have the calling application implicitly link to that DLL. Put the other functions that the calling application does not need right away into another DLL and have the application explicitly link to that DLL.

 
39. There's a memory leak in my regular DLL, but my code looks fine. How can I find the memory leak? 
One possible cause of the memory leak is that MFC creates temporary objects that are used inside message handler functions. In regular DLLs, MFC does not automatically release memory allocated for these objects.

 
40. How do I create a modal dialog box from within a regular DLL? 
When creating a modal dialog box from within a regular DLL statically linked to the MFC, you must pass a valid parent window object to the CDialog constructor.

 
41. How do I export data from a DLL? 
It is possible for a Win32-based application to be able to address DLL global variables directly by name from within the executable. This is done by exporting global data names in a way that is similar to the way you export a DLL function name.

42. How do I convert my USRDLL to a regular DLL that uses the MFC shared library?
Note that the term USRDLL is no longer used in the Visual C++ documentation. A regular DLL that is statically linked to MFC has the same characteristics as the former USRDLL.
Converting your DLL to dynamically link to the MFC libraries requires more than just rebuilding the DLL with the MFC shared library.

 
43. How do I port my 16-bit DLL to a Win32 DLL? 
If you have built 16-bit DLLs for Windows 3.x, you should find that building 32-bit DLLs is more convenient. Visual C++ offers more direct support, which can save you several steps in DLL creation.

 
44. What is GetProcAddress?
Processes explicitly linking to a DLL call GetProcAddress to obtain the address of an exported function in the DLL. You use the returned function pointer to call the DLL function. GetProcAddress takes as parameters the DLL module handle (returned by either LoadLibrary, AfxLoadLibrary, or GetModuleHandle) and takes either the name of the function you want to call or the function's export ordinal.
Because you are calling the DLL function through a pointer and there is no compile-time type checking, make sure that the parameters to the function are correct so that you do not overstep the memory allocated on the stack and cause an access violation. One way to help provide type-safety is to look at the function prototypes of the exported functions and create matching typedefs for the function pointers.

 
45. What is FreeLibrary and AfxFreeLibrary?
Processes explicitly linking to a DLL call the FreeLibrary function when the DLL module is no longer needed. This function decrements the module's reference count and, if the reference count is zero, unmaps it from the address space of the process.
MFC applications should use AfxFreeLibrary instead of FreeLibrary to unload an extension DLL. The interface (function prototype) for AfxFreeLibrary is the same as FreeLibrary.

 
46. What are the Module States of a Regular DLL Dynamically Linked to MFC ?
The ability to dynamically link a regular DLL to the MFC DLL allows some configurations that are very complicated. For example, a regular DLL and the executable that uses it can both dynamically link to the MFC DLL and to any extension DLLs.
This configuration poses a problem with regard to the MFC global data, such as the pointer to the current CWinApp object and handle maps.
Before MFC version 4.0, this global data resided in the MFC DLL itself and was shared by all the modules in the process. Because each process using a Win32 DLL gets its own copy of the DLL's data, this scheme provided an easy way to track per-process data. Also, because the AFXDLL model presumed that there would be only one CWinApp object and only one set of handle maps in the process, these items could be tracked in the MFC DLL itself.

47. How to Create a Resource-Only DLL ?
A resource-only DLL is a DLL that contains nothing but resources, such as icons, bitmaps, strings, and dialog boxes. Using a resource-only DLL is a good way to share the same set of resources among multiple programs. It is also a good way to provide an application with resources localized for multiple languages (see Localized Resources in MFC Applications: Satellite DLLs).

To create a resource-only DLL, you create a new Win32 DLL (non-MFC) project and add your resources to the project.

* Select Win32 Project in the New Project dialog box and specify a DLL project type in the Win32 Project Wizard.
* Create a new resource script that contains the resources (such as a string or a menu) for the DLL and save the .rc file.
* On the Project menu, click Add Existing Item, and then insert the new .rc file into the project.
* Specify the /NOENTRY linker option. /NOENTRY prevents the linker from linking a reference to _main into the DLL; this option is required to create a resource-only DLL.
* Build the DLL.

The application that uses the resource-only DLL should call LoadLibrary to explicitly link to the DLL. To access the resources, call the generic functions FindResource and LoadResource, which work on any kind of resource, or call one of the following resource-specific functions:

* FormatMessage
* LoadAccelerators
* LoadBitmap
* LoadCursor
* LoadIcon
* LoadMenu
* LoadString
The application should call FreeLibrary when it is finished using the resources.

 
48. What is Active Technology and DLLs
Active technology allows object servers to be completely implemented inside a DLL. This type of server is called an in-process server. MFC does not completely support in-process servers for all the features of visual editing, mainly because Active technology does not provide a way for a server to hook into the container's main message loop. MFC requires access to the container application's message loop to handle accelerator keys and idle-time processing.
If you are writing an Automation server and your server has no user interface, you can make your server an in-process server and put it completely into a DLL.

 
49. Whats is Automation in a DLL
When you choose the Automation option in the MFC DLL Wizard, the wizard provides you with the following:

* A starter object description language (.ODL) file
* An include directive in the STDAFX.h file for Afxole.h
* An implementation of the DllGetClassObject function, which calls the AfxDllGetClassObject function
* An implementation of the DllCanUnloadNow function, which calls the AfxDllCanUnloadNow function
* An implementation of the DllRegisterServer function, which calls the COleObjectFactory::UpdateRegistryAll function

 
50. Localized Resources in MFC Applications: Satellite DLLs ?
MFC version 7.0 and later provides enhanced support for satellite DLLs, a feature that helps in creating applications localized for multiple languages. A satellite DLL is a resource-only DLL that contains an application's resources localized for a particular language. When the application begins executing, MFC automatically loads the localized resource most appropriate for the environment. For example, you could have an application with English language resources with two satellite DLLs, one containing a French translation of your resources and the other containing a German translation. When the application is run on an English language system, it uses the English resources. If run on a French system, it uses the French resources; if run on a German system, it uses the German resources.

To support localized resources in an MFC application, MFC attempts to load a satellite DLL containing resources localized to a specific language. Satellite DLLs are named ApplicationNameXXX.dll, where ApplicationName is the name of the .exe or .dll using MFC, and XXX is the three-letter code for the language of the resources (for example, 'ENU' or 'DEU').

MFC attempts to load the resource DLL for each of the following languages in order, stopping when it finds one:

1. (Windows 2000 or later only) The current user's default UI language, as returned from the GetUserDefaultUILanguage() Win32 API.
2. (Windows 2000 or later only) The current user's default UI language, without any specific sublanguage (that is, ENC [Canadian English] becomes ENU [U.S. English]).
3. The system's default UI language. On Windows 2000 or later, this is returned from the GetSystemDefaultUILanguage() API. On other platforms, this is the language of the OS itself.
4. The system's default UI language, without any specific sublanguage.
5. A fake language with the 3-letter code LOC.

If MFC does not find any satellite DLLs, it uses whatever resources are contained in the application itself.
As an example, suppose that an application LangExample.exe uses MFC and is running on a Windows 2000 multiple user-interface system; the system UI language is ENU [U.S. English] and the current user's UI language is set to FRC [Canadian French]. MFC looks for the following DLLs in the following order:

1. LangExampleFRC.dll (user's UI language).
2. LangExampleFRA.dll (user's UI language without the sublanguage, in this example French (France).
3. LangExampleENU.dll (system's UI language).
4. LangExampleLOC.dll.

If none of these DLLs are found, MFC uses the resources in LangExample.exe.

 

 
Subscribe Newsletter
Register to the site for free, and subscribe to the newsletter. You will receive new articles and special content not available elsewhere on the site, right into your e-mail box!