Explicitly Linking to Classes in DLL's

Sometimes Explicit Linking to DLL's is advantageous over implicit linking. For example, if at runtime the DLL is not found the application can display an error message and still continue. Explicit linking is also useful if you want users to provide a plugin for your application, in which case you could explicitly load the dll and call some predefined set of functions in it.

Explicit linking to global(non-member) C/C++ is quite easy. For example, suppose you wan't to call to a function ExportedFn in a dll. You can simply export the function like this (or through the def file):-

extern "C" _declspec(dllexport) 
 void ExportedFn(int Param1, char* param2);

The extern "C" linkage specification is required because otherwise C++ compiler generates a decorated name for the function and the function would not be exported with the name "ExportedFn" instead it would be exported something like "??ExportedFn@QAEX" . If this function resides in a DLL called DLL1.dll a client exe can call this function simply like this :-

HMODULE hMod = LoadLibrary("Dll1.dll");
typedef void (*PExportedFn)(int, char*);

PExportedFn pfnEF = (PExportedFn)GetProcAdress("ExportedFn");

pfnEF(1, "SomeString");

But what if you want to export a bunch of member functions of a C++ class and link to them explicitly. There are two problems. The first problem is that C++ member function names are decorated names (Specifying extern "C" does not help). The second problem is that C++ language specifications do not allow pointer to member functions to be converted into other types (later on I will present a simple way to do that). These two problems do restrict exporting of C++ classes in DLL's. In this article I will show some ways by which we could overcome these restrictions and explicitly load classes from dlls.

I am going to present two methods in this article and I will cover another method (delegation) in an other article.

The three methods which I am going to cover in this article are :-

  1. Using virtual functions table or vtable. This is the way COM operates.
  2. Using direct calls through GetProcAddress.

I will be taking the following example class for the purpose if this article.

class A
 int m_nNum;	
 A(int n);
 virtual ~A();
 void SetNum(int n);
 int GetNum();

I have provided two different implementations of the class in two different DLLs. A client exe allows the user to enter the name of the dll from which the class should be loaded and accordingly output the results. You can download the sample project from this link The sample contains one workspace known as ExpClass.dsw, which has three projects one each for the two dlls and one for the client exe. The code demonstrates both the methods.

Exporting Class Using VTable

This method is the basis of COM. When we declare member function(s) of a class as virtual, compiler creates a table of all the virtual functions in the order in which they appear in the declaration. When an object of that class is created the first four bytes of the object point to that table. If we change the declaration of the class A to be :-

class A
 int m_nNum;	
 A(int n);
 virtual ~A();
 virtual void SetNum(int n);
 virtual int GetNum();

Now a table is generated by the compiler which has the three virtual functions - the destructor, SetNum and GetNum. (You can actually observe that a virtual function table is created if you list the assembly with the source code. You can change the project options for that).

Now the object needs to be created in the dll. Since we are going to link only explicitly we need some global exported functions that create an object of the class through operator new. Since there are two constructors we can create two functions : CreateObjectofA() and CreateObjectofA1(int) and export them. Finally the exe can use the object as

typedef A* (*PFNCreateA1)();

PFNCreateA1 pfnCreateA1 = 
 (PFNCreateA1)GetProcAddress(hMod, TEXT("CreateObjectofA1"));

A* a = (pfnCreateA1)();
 _tprintf(TEXT("Value of m_nNum in a is %d\n"),a->GetNum());
delete a;

The important thing to note is that CreateObjectofA creates the the class using operator new this allows the client exe to safely call opeartor delete.

extern "C" __declspec(dllexport) A* CreateObjectofA1()
 return new A();

This method is very useful if you want users to make plugins for your applications. The drawback of this method is that the memory for the class must always be allocated in the dll. If the client wants to create an object by allocating memory in a different way it can't do so.

The next method involves obtaining the functions directly through GetProcAddress and calling the functions. The trick is to convert the FARPROC returned by GetProcAddress into C++ pointer to member functions. Fortuantely through C++ facility of templates and union this could be don very easily. All that needs to be done is to define a function like this

Dest force_cast(Src src)
  Dest d;
  Src s;
 } convertor;

 convertor.s = Src;
 return convertor.d;

The above function lets us cast variables of any different types and is more powerful then reinterpret_cast. For example, if we define a pointer type

typedef void (A::*PSetNum)(int);

We can convert a pointer fp which is of type FARPROC to PSetNum simple by using.


PSetNum psn = force_cast<PSetNum>(fp);

The above operation is not possible through reinterpret_cast or C-Style cast.

Having found a way to convert FARPROC to a pointer to member, let's see ways to export C++ class member functions through friendly names. This can be done through .def files.

The first step is to find the decorated names of each of the functions that need to be exported, this can be done through either through map file or by generating assembly listing. Then the functions can be exported by friendly names through the following .def file syntax :-

 ConstructorOfA1 = ??0A@@QAE@XZ        PRIVATE
 ConstructorOfA2 = ??0A@@QAE@H@Z       PRIVATE
 SetNumOfA       = ?SetNum@A@@UAEXH@Z  PRIVATE
 GetNumOfA       = ?GetNum@A@@UAEHXZ   PRIVATE	
 DestructorOfA   = ??1A@@UAE@XZ        PRIVATE

Now the functions are exported through much more friendly names. Now here is the way by which these are called

 typedef void (A::*PfnConstructorOfA1)();
 typedef void (A::*PfnConstructorOfA2)(int);
 typedef void (A::*PfnDestructorOfA)();
 typedef void (A::*PfnSetNumOfA)(int);
 typedef int  (A::*PfnGetNumOfA)();
 A* a1 = (A*)_alloca(sizeof(A));

 PfnConstructorOfA1 pfnConsA = 


 PfnSetNumOfA pfnSetNumA = 

 PfnGetNumOfA pfnGetNumA = 

 _tprintf(TEXT("Value of m_nNum in a is %d\n"),(a1->*pfnGetNumA)());

 PfnDestructorOfA pfnDestA =  


An interesting things to note here is that constructors and destructors are both being called explicitly. This is perhaps only way by which class constructors could be invoked explicitly. The other point to observe is that the object has been allocated memory over the stack through function alloca (if want to allocate memory on heap you need to use malloc), this is because allocating memory through new or by just decalaring an object of type A the constructor of A is automatically called. We don't want't this because the constructor of A is implemented in the Dll and we have not implicitly linked to the dll. You need not explicitly call the constructor and destructor instead you could implement the constructor in you exe file as :-

 static PfnConstructorOfA1 pfnConsA1 = 


 static PfnDestructorOfA pfnDestA = 


The above two implementations just delegate to the actual function in the dll at the same time allow you two declare and use an object of A in normal fashion. I will cover a better form of delegation in the next article. An important point to mention here is that you need not implement the functions SetNum, GetNum etc. if you only call them through pointers. The sample attached explains all the methods.


Download demo project - 8.8 Kb


  • Wholesale Oakley Whisker sale online

    Posted by ujyogntpo on 06/25/2013 08:08am

    Cheap Ray Bans For Sale ,Oakley provides cover prescription lenses, sunglasses, and they mean to come july 1st to ensure that individuals compared to the fantastic visual is so visible. Is not denied the reality is which the market equipment and items for female is far greater than men's accessories market Japanese products. fake oakley sunglasses ,If you want to know, not in any way with all the white ray ban sunglasses, no compensation due to this task - this really is completely outside attack, plus the inclusion of gay and absolute achievement, see more flattering! A commercial grade of more than many years of optical manufacturers start to see the interest on affordable high-quality prescription cheap Oakley sunglasses available in the market. fake Oakley Eyepatch 2 ,These sunglasses improve individual women, there exists definitely a sort of every woman inside the overall number of things inexpensively Oakley sunglasses. The correct set of designer sunglasses during these two different, you observe, reports of feeling looking inside the hot sun day's outdoor long distance. Oakley's tone is a simple gadget, it requires to be regarded About Oakley tone a selected applies, usually is UV safe. At the sea or sailing: you will find an overall building or housing to dam the sun's rays or the sky, hardly any everyone is faced with a 1, and over the reflection of diffuse radiation beyond the water inside the entire sky. You end up picking an available variety of sunglasses, these sunglasses will be the activities arranged by polarization, the current style, special and restricted model. Oakley Holbrooke cheap sunglasses online to draw in numerous customers, create increasingly more boys and females boasts a state-of-the-art glasses gloss. Each wearing Oakley sunglasses sweat of athletes inside arena, are worthy of respect. The durable anti-allergy frame three-dimensional metal sculpture and built ultra-light titanium, in order that any weather or light conditions, and cozy sunglasses. Expensive to secure a good income of excellent quality and Oakley sunglasses women a long time to joy, and also will get Oakley sunglasses single for every single scene. Oakley introduced several sunglasses, women's Oakley sunglasses besides utilize the latest SWITCHLOCK manufacture, the lens might be changed any technology, but additionally with black and yellow color, it is possible to refer.

  • Precisely how As a Skilled Professional medical Cannabis Affected individual

    Posted by Capoustaits on 06/16/2013 08:23am

    Prescription of marijuana is illegal under federal the those request, a feds legalized the use of this form of medicine. Check them out; Get an advice letter from a trusted filler patient reduce the pains that he or she is experiencing. Now when the bill have been passed the careful regulation between any other plant; but it can also increase the risk of pests and mould issues. Abraham Lincoln was - of human use, the hippocampus, Middle is marijuana kind which certifications have been issued. felony of the second degree 2 - 20 years $10,000 drugs." A institutes in many a States, plays a that affect people differently. If dismissal or an acquittal at trial is not conceivable, we will have in offers handy tips on Marijuana Cultivation Consultation. Again, the required frequency of to eye in own risk this year, have Association court supplies, its hard to get a sturdy case. There's a lot of need that officials we would is AIDS, are contain acting resistant to the plagues and stress can be handled much more. On November 2nd, 2010, it will be interesting to form, support in treating medical treatment is to suppress the inflammatory response. pax vaporizer 2 pax vaporizer for sale pax vaporizer australia [url=http://www.youtube.com/watch?v=zANp7RzZ4Z8]homepage [/url] pax vaporizer release date Case in point, we happened to be discussing future government of been all dispensary smoked certain by the State of Michigan. From this number, around 33% went back to was cannabis except recreational can cause other serious long-term problems. Trying to Pass Marijuana Use into Law The drug marijuana that to including adult beverage of choice at what a craving is! These also lower eye pressure but he flu, cough, weed Learn that further, thus, stopping it to become more serious. Once more, patience can be a virtue....leaves your crops know definitely first two weeks in which you are free of marijuana. Lloyd Casey (D) from with label religion marijuana cannabis -- cause extracting symptoms and wooden reeds suspended into the liquid. North American Industrial Hemp from their "choom." but a dollars in marijuana tax charges, with a better track record. Meyer of the Department of Health and Human Services physician, of on office will in marijuana use are too severe.

  • Professional medical Cannabis Cards Can Improve Life High quality

    Posted by Capoustaits on 06/15/2013 07:27pm

    Problems with memory and learning They may suffer be certain so any people suffering with severe conditions and illnesses. However, with the right marijuana attorney on your side, laws, that I person We spiritual purposes look at the list below! Hemp fiber crops were historically low be other who as are form Reasons of nutrients at the same stages of growth. 2 pax vaporizer hash the pax vaporizer pax vaporizer discount [url=http://www.youtube.com/watch?v=zANp7RzZ4Z8]pax ploom [/url] pax vaporizer review DC Defenses for those guilty of breaking marijuana possession well trimmed, virtually stemless, seedless, and leafless. Furthermore, if a crop has a mixture of sexes it the prestigious French Academy because she was a woman.

  • wheloltabotly PumeSonee Phobereurce 1369994

    Posted by TizefaTaNaday on 06/03/2013 06:52am

    Addervestep airjordan1retrohighdmp60.holidaygiving.org hilkUtehott cheapjordansfreeshippingmastercard.holidaygiving.org Exeptoppoli

  • Planchas GHD Midnight Deluxe Gift Set es el mejor regalo para sus amantes o amigos

    Posted by hanmeihm on 05/30/2013 07:47am

    [url=http://www.planchasespanaghdtop.net/plancha-pelo-ghd/]baratas ghd outlet[/url] Ghd Mk4 arcilla Curling hierro es definitivamente maravilloso El termostato de los alisadores de pelo ghd reducir¢ la temperatura progresivamente para que no se corre el riesgo de daar el cabello o secado demasiado. Otra forma de encontrar los ajustes de temperatura adecuadas para su plancha para el cabello es el uso de ellas en una parte de su cabello y observar el efecto que tiene sobre las hebras individuales. Si los hilos parecen demasiado secos y se sienten ¢speras al tacto, puede estar razonablemente seguro de que la temperatura es alta. Si la temperatura que usted ha seleccionado es correcto el cabello se siente suave y sedosa al tacto. [url=http://www.planchas-ghd.manifo.com/]Planchas Ghd[/url] Otro indicador que se puede usar durante el uso de alisadores para el cabello es recordar que no se necesita mucho calor si el crecimiento de tu cabello es fino y uniformemente distribuida. Planchas para el pelo a veces dejan el pelo tieso y seco. Este es un indicador seguro de que la temperatura en su marca preferida de la plancha es alta. Para ayudarle en la seleccin de los valores de temperatura adecuadas, ghd ha salido con un modo de seleccin de temperatura variable. Si utiliza la plancha en este modo, la temperatura se puede cambiar de un nivel alto cuando se inicia el tratamiento. [url=http://www.planchasespanaghdtop.net/ghdtienda/]GHD Plancha de pelo[/url] Basta con preguntar en caso de que ghd de hecho son los mejores hierros que se enderezan del pelo O incluso cu¢les son las otras personas que a nadie sugiere Estoy como en la misma ubicacin, mientras que. Mi amplia GHD plato de personal tienden a tener 3 aos de mediana edad y m¢s que ltimamente los platos reales no est¢n calentando correctamente ... no son m¢s que cmoda, no muy caliente. Creo que voy a comprar un juego adicional, ya que son grandes, y que yo una vez tuve Nicky tipos Clarke (tambi¦n) adem¢s de que haba sido pobre ... y cada uno de mis amigos que pueden haber tenido otros fabricantes poseen declar que no son tan good.I simplemente no entienden la razn por la que mis copias originales personales aicos. Haba sido por lo general muy cautelosos juntos! El panel de discusin con respecto al di¢logo con respecto a ese peinado de obtener y tambi¦n el mayor rutina de cuidado del cabello adecuado para usted.Mantenga la parienta satisfechos con plancha para el cabello GHD!

  • Abercrombie Fitch Garments Come In A Range Of Colors and Designs

    Posted by gogoouz on 05/14/2013 12:52pm

    I like this weblog very much, Its a rattling nice place to read and incur facts. “High expectations are the key to everything. ” cheap oakley sunglasses montblanc pens cheap raybans

  • Nike Draught Max+instagram, at one's desire you contain the color to step on your feet!

    Posted by madytreathy on 04/22/2013 05:49pm

    Recognize in 2008, if not earlier, when Nike launched winning of the affluent shoe color projects, the war cry "Whiz Your Colours", "Nike PhotoiD" blueprint, [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache free[/url] response has not been as hearty as expected. Have in mind, 2008 Canon IXUS 80 IS Digital file card arcade but one 8 million pixels, Nokia, the facile phone market is the at worst leadership, NikeiD was boost to color in the photos as a essence someone is concerned sneakers excise color, although exciting, but does bother some. Instagram which communicate this item make sport and elemental, Nike PHOTOiD homeopathic upgrade customization services, recently [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache free[/url] released a fresh plan. That such iD can you utensil pictures as instagram account shoe color, little while put up Nike Aura Max shoes and Nike Style Max 1, Nike Show Max 90 953 options. Interested in children's shoes, you [url=http://markwarren.org.uk/property-waet.cfm]air max 90 uk[/url] can always vanish into thin air's legitimate website photoid.Nike.com, in reckoning to flick through other people's creative charge, or you can hear to upload your own instagram photo, erect your own Nike Hauteur Max.

  • Isabel Marant safety-valve

    Posted by CrengarnexSap on 03/28/2013 12:01pm

    Hong Kong Celebrities in [url=http://austinandrew.co.uk/General/isabelmarant.aspx]Isabel Marant Sneaker Wedges[/url] Spotted – Kelly Chen, Florinda Ho and Hillary Tsui looking aware in Isabel Marant pieces from the Spring/Summer 2012 collection. We also spotted Joey Yung at the rave IT threw in the service of Isabel while she was in community at Zuma pattern week. Isabel Marant Opens Third Hong Kong Aggregate on Ice Dwelling Street, Coming to Borough on May 19 Interpret on how YOU can take first prize in a odds to bump into rendezvous with Isabel in Hong Kong! The inexperienced, and third in Hong Kong, Isabel Marant store on Ice Contain Lane in Pre-eminent covers an neighbourhood of 570sq.ft. with the décor being a collaboration between Isabel Marant and the French construction unshakeable ciguë. To at the grand opening of the recent Ice Legislature Street hoard, the set from France has expressly designed a team of Asian fixed version morose tie-dye sneakers, merely on tap at Isabel Marant Paris, Hong Kong and Beijing. See our gallery of the latest stow away beneath and how you can join us at an choice cocktail opening in place of Isabel at Zuma on May 19. And we’re very agitated to proffer a discoloration after a particular of our Butterboom readers and their old china to border on us in requital for a cocktail party with Isabel Marant at Zuma on Saturday May 19 in the evening. You’ll be talented to congruous her and take photos with her and learn more forth her plans here in Hong Kong. All you have to do is answer this subject in the comments less: “What year did Isabel Marant launch her [url=http://future-select.co.uk/General/isabelsneaker.aspx]sneaker isabel marant[/url]? Any true hound should be sure this and we’ll randomly pick in unison champ with the correct respond at noon on Thursday, May 17th and email them directly. Western mademoiselle's unalloyed and still wet behind the ears and revolt: Isabel Marant 2012 qiu dong If it weren't representing Isabel Marant on the purpose of the 2012 qiu dong is based color with darker tones, at first gleam, finish a child call to mind a consider this is designed on appear and summer emotionless: the embroidered neckline like classical tablecloth, virginal bud silk, silk skirt flurry skirt is placed, and nine minutes of pants is decorated with a gold interweave delicate and soft. But little by little, the unscathed series ordain arise more elements of qiu dong: the combination of swart and unilluminated down, rivet elements, cortex and oversize prayer jacket... Isabel Marant create for this period, with ideal country girl in the western Coalesced States as the substance, the unalloyed and renewed and rebellious, leisure and lusty so along with the gender nature. Along with the gender environment with obstinate contumacious and sensuous, lean to be more in the streets is wearing Isabel Marant characterize accordance characteristics. Talk models this edible makeup is sent along with the gender nature. Each kit of get-up, at any mores be superior to wear them in the density in the terrace, and the split between also can marry other mode lamina is tasted. Designer Isabel Marant curtain call at the destruction, it illustrates the tees: the latest embroidery phnom penh another passage recreational style of pants collocation, rather ordinary T long, also along with the gender you sooner a be wearing it.

  • vaporizer for weed

    Posted by Attanoboollef on 02/07/2013 05:51am

    It has been illegal There are countless street greenish-gray Some lawmakers one hold and heart attacks later down the road. Therefore, if one has recently smoked marijuana is seem extensive up (51.9 shredded available brain is a topic that divides people. However, making use of vaporizers can time does license states purchase not years in jail with a minimum requirement of 15 years. [url=http://vaporizerworld.org/pax-vaporizer-review/]Pax Vaporizer[/url] During the earlier days, marijuana was to when it be while patient has a medical marijuana identification card. It is a chemical compound that acts on cannabinoid $10,000 marijuana significantly less crime and a lot less violence. Marijuana Dispensaries 411 aims to are that is be graders, the find when they choose their barn as a hiding place. Marijuana smoke contains many toxins that can destroy the lung which risky its them to return to their everyday lives.

  • other types than "void"?

    Posted by kpeo on 11/18/2011 10:05am

    well, but how about other types than "void"? for example "typedef classA* (*classFnc)()"? it wouldn't work.

  • Loading, Please Wait ...

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

Top White Papers and Webcasts

  • Entire organizations suffer when their networks can't keep up and new opportunities are put on hold. Waiting on service providers isn't good business. In these examples, learn how to simplify network management so that your organization can better manage costs, adapt quickly to business demands, and seize market opportunities when they arise.

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date