Tips for using Dynamic Link Libraries (DLLs) with MFC

This documents intends to give a beginner some knowledge that can be helpfull when designing a project to the Windows plataform. When I start a new project I try to let all the code that seams to be the most changeable in a DLL. This give me the power to change the project having to compile and distribute the minimum piece of code.

But to do this work properly there are some tips that must be followed. Many of you might be asking asking Why not simply use COM ? The answer is that, of course, COM is a great choice in certain situations. However, DLLs are still a very viable alternative as well. Therefore, in this article. I hope to illustrate just when you should use DLLs and exactly how to use them within the framework of an MFC application.

A big problem of DLLs (specially those that use MFC) are the debug and release version. These versions are incompatible. You probably had the problem of running the debug application version with the DLL release version. The whole world gets crazy!! The best way, in fact the way Microsoft does, is to give diferent names to the DLLs. So the release DLL stays with the Visual C++ project name and the debug version would look like [Project Name]D.DLL. Using this approach you can send the two DLLs to the system directory and be happy. Those are the steps needed to achieve this (suposing the project name is AAA):

  1. Copy the AAA.def to AAAD.def and change all the AAA to AAAD;
  2. In the Project/Settings, select Win32 Debug
  3. Under the tab Link change the Output file name to AAAD.DLL;
  4. Below in this property page you can see something like:
    /def:".\AAA.def" /out:"Debug/AAAD.DLL"
    Change to:
    /def:".\AAAD.def" /out:"Debug/AAAD.DLL"

Now the the debug version will create AAAD.lib and AAAD.DLL files. When I create a DLL I create an include header to it (I think everybody does), which I named DLL header. This header has all the exported classes definitions. And to be more efficient I include the linking stuff in it, so to use the DLL you doesnt have to add the lib file to the Project Settings. My header looks like:

#ifndef DEF_MUDASDASDASDASDAS
#define DEF_MUDASDASDASDASDAS

#ifdef _DEBUG
#pragma comment(lib, AAAD.lib)
#else
#pragma comment(lib, AAA.lib)
#endif

//... the classes definitions goes here

#endif //MUDASDASDASDASDAS

Programming for Changes

The prefered kind of DLL used to export classes are the MFC extension DLLs. By using this you can easily instanciate a classe that is within a DLL. To do this you just declare the class like this:

class AFX_EXT_CLASS CFoo
{
 //...
}

In the application that uses this class you just include the DLL header and everything is cool. The problem is: everytime you need to include a member variable or a method to an exported class you have to change the DLL header, which means recompile all those who use the DLL. To new methods I dont know a way to overcome this recompilation, but for new variables theres a way.

Instead of declaring the member variables directly to the class body, you create a kind of implementation class, like the sample code:

class CFooImpl;
class CFoo
{
protected:
 CFooImpl* m_pThis;
};

So the CFooImpl class doesnt need to be declare to those how use this DLL. The implementation of CFoo would look like:

class CFooImpl
{
public:
 CString m_sName;
};

CFoo::CFoo()
{
 m_pThis = new CFooImpl;

 m_pThis->m_sName = _T("Unknown");
}

CFoo::~CFoo()
{
 delete m_pThis;
}

Another method to be prepared for changes is to use inteligents structs the way the Windows API does. So you declare a method that has an LPVOID as in and out parameter. Those pointers are address of structs instances. The trick is to define as the first struct member a DWORD regardings its size. This way you know which data is expected.

 
typedef struct tagCHANGEABLE
{
 DWORD dwSize;
 long lBytes;
}CHANGEABLE, *LPCHANGEABLE;

BOOL CFoo::Method(LPVOID lpIn)
{
 LPCHANGEABLE lpChangeable = (LPCHANGEABLE)lpIn;

 if (lpChangeable->dwSize == sizeof(CHANGEABLE))
 {
  //...
  return TRUE;
 }

 return FALSE;
}

Using it:

CFoo myFoo;

CHANGEABLE changeable;
memset(&changeable, 0, sizeof(changeable));

changeable.dwSize = sizeof(changeable);

myFoo.Method(&changeable);

DLL Loaded When Needed

Sometimes you have uncommon situations that you need to call a dialog or create a class instance. So you decide to put those in a DLL, but you dont want it to be loaded when the application gets executed. You want to load the DLL when needed (COM). This kind of DLL I call Dynamic DLL (stupid name I know Dynamic Dynamic link libraries). So you declare the exported function as:

__declspec( DLLexport )
void MyExportedFunc(DWORD dw)
{
 //...
}

We need to include this function in the defs files (debug and release). The debug def file would look like this:

; AAAD.def : Declares the module parameters for the DLL.

LIBRARY      "AAAD"

DESCRIPTION  'AAAD Windows Dynamic Link Library'

EXPORTS
 MyExportedFunc @1
 ; Explicit exports can go here

Now to use this function we need to load the library, find the function entry point and call it.

typedef void (*MYFUNC)(DWORD);  

#ifdef _DEBUG
 HINSTANCE hDLL = AfxLoadLibrary("AAADLLD");
#else
 HINSTANCE hDLL = AfxLoadLibrary("AAADLL");
#endif

if (hDLL)
{
 FARPROC pnProc = GetProcAddress(hDLL, "MyExportedFunc");
 MYFUNC pnMyfunc = (MYFUNC)pnProc;

 pnMyfunc(0);

 FreeLibrary(hDLL);
}

Remember that to use show a dialog you must take care of the resource stuffs (AfxSetResource..). You can use this approach to create class instances. The class definition must use pure virtual functions (to avoid unresolved external symbol). It is just like COM.

The class definition should look like this:

class CFoo
{
public:
 virtual void Initialize (CString sName) = 0;
};

You implement this "interface" with another class that is not visible through the DLL header file.

class CFooImp  : public CFoo
{
public:
 CFooImp();
 virtual ~CFooImp();

 void Initialize (CString sName)
 {
  m_sName  = sName;
 }

protected:
 CString m_sName;
};

To create an instance of this class (interface) you create an exported function.

__declspec(DLLexport)

CFoo* CreateFoo(DWORD dwVersion)
{
 if (dwVersion == CURRENT_VERSION)
  return new CFooImp;

 return NULL;
}

The application creates the class instance like this:

typedef CFoo* (*MYFUNC)(DWORD);  

#ifdef _DEBUG
 HINSTANCE hDLL = AfxLoadLibrary("AAADLLD");
#else
 HINSTANCE hDLL = AfxLoadLibrary("AAADLL");
#endif

if (hDLL)
{
 FARPROC pnProc = GetProcAddress(hDLL, " CreateFoo");
 MYFUNC pnMyfunc = (MYFUNC)pnProc;

 CFoo* pFoo = pnMyfunc(0);

 pFoo->Initialize(_T("Hi"));

 delete pFoo;

 FreeLibrary(hDLL);
}

Remember that you cannot free the library until you deleted the CFoo instance.

Conclusion

These examples explained the powers of well designed DLLs. But if the whole project has a bad design no miracle will make your applications easy to change and update. The good design is the first and most important step to the successfull project.



Comments

  • Additional Christian Louboutin added juin paire de FRED Teem Hommes automne / hiver 2012 AU 14 nouveau printed poney mocassin Jordan

    Posted by Vetriatszy on 03/15/2013 01:18pm

    amazing choice to achieve Abercrombie revenue even although abercormbie have an overabundance than 1,000 outlets globally,employing up to date misery of the universe industrial state's borders,some expansion display had to be postponed and additionally interim the division terior chain as Ruehl ended up being closed on account of the high cost for going. we are all aware, Abercrombie fasion clients are mainly based on the stores in enormous county, this also often causes large click over here onto rent,Labours with the help of getting the whole sequence, clients abercrombie highlighted however the dog's entire process affordability revenue way those quite a few years, folks selpublishmly commissions or alternatively any kind of low named sustaining trademark enjoy. and also we needed to say that the majority of abercrombie which has made favourable discuss its model to trap ones prefer of teenager and quality of its solution, truthfully to most of individuals, Abercormbie is an inexpensive luxury, individuals could possibly be a more happy, whenever "Abercormbie available for sale" properly developed more frequently. the fabric among abercormbie T-t-shirts the best idea home owner in all of the special type abrcrombie associated with technique is mainly according to 100% cotton, genuine no big-techie artifical style focused, We can observe with out darkness of anxiety that the content expense of a bit of polos is not really before two united states dollar dollars, much to find cotton of the world. in the western world labours, Because lots of the clothing is came down with mamufactured from inside the under-developed gets,Which aren't composing cost for getting

    Reply
  • Impart Jordan V Repulsive Awaken Red Mephistophelian qui sortira officiellement le 26 janvier 2013 Jordan

    Posted by Vetriatszy on 03/14/2013 01:38pm

    Petersburg's First evening time factors american idol Finalist emmanuel Lynche mirielle Lynche, st. Petersburg, Fla. ancient to Season 9 american idol Finalist, head lines usually the annual upcoming summers eve activities within the local towards Dec. 31, 2010. Lynche has become booked to accomplish on the principal step at northern Straub park your car prior the First Night thousand finish fireworks at nighttime. just for 18 lots of, st. Pete seems to have written involving Florida's most First day merrymaking events. the foregoing spouse-user friendly, booze-Free extravaganza blends a nice of varied entertainments, like hands-by martial arts styles and after that projects, food shopping cart march, exercise involved with preference operatic arias, Puppet live theatre along with favorite bubble stomp. competitions become scheduled along at the boat dock, public in brilliant martial arts styles, Baywalk, straub park system coupled with other general. Petersburg wedding venues as well as includes tampa Bay's maximum fireworks this website arrangement. expect guidance on events in your area? catch e-mailings status updates in the event that absolutely new content is shared by way of clicking on the 'Subscribe' key around. go to this page to speak to your polk bay holidays Examiner

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Agile methodologies give development and test teams the ability to build software at a faster rate than ever before. Combining DevOps with hybrid cloud architectures give teams not just the principles, but also the technology necessary to achieve their goals. By combining hybrid cloud and DevOps: IT departments maintain control, visibility, and security Dev/test teams remain agile and collaborative Organizational barriers are broken down Innovation and automation can thrive Download this white paper to …

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds