C++ Callback Demo


This article was contributed by Elmue.

Environment: Pure C++. Runs on Windows, Mac, Linux, and so on.

Introduction

This fully functional example shows how in C++ callbacks can be done in an absolutely flexible way!

This demo is written in Visual Studio 6 but the Callback class is platform independent and also runs under Linux, Mac, and so forth....

Callbacks in C++ are not as simple as in C. Pure C functions are from the type __cdecl. C++ functions are from the type __thiscall. (They differ in the way how they pass arguments on the stack.)

In C++, you have classes and, additionally, instances of classes. Every instance uses its own memory area for storing class variables. The pointer to this area of variables is the "this" pointer. It represents the instance. Every time you call any C++ function, the "this" pointer is passed to the function as an invisible parameter! (M$ Visual Studio 6 uses the processor register ECX to pass the "this" pointer.)

So, in C++ it is not enough to store the address of the function, which you want to call back. You also have to store the "this" pointer!

Using the Callback Class

You can include "Callback.h" into your project. The usage it is very simple because the cCallback class has only two member functions: SetCallback() and Execute(). You can understand the following examples without knowing what is happening inside cCallback.

cMyProject.h:

#include "callback.h"

private:
    // the functions of your project
    void CallbackFox   (int Param);
    void CallbackRabbit(int Param);
    void TestTheCallback(cCallback *pCallbackFunction, int Param);

    // Some instances of the Callback class
    TCallback<cMyProject> i_Callback_1;
    TCallback<cMyProject> i_Callback_2;

cMyProject.cpp:

void cMyProject::CallbackRabbit(int Param)
{
    char Buf[50];
    sprintf(Buf, "Now I'm in Rabbit with Param %d !\n", Param);
    printf(Buf);
}

void cMyProject::CallbackFox(int Param)
{
    char Buf[50];
    sprintf(Buf, "Now I'm in Fox with Param %d !\n", Param);
    printf(Buf);
}

void TestTheCallback(cCallback *pCallbackFunction, int Param)
{
    pCallbackFunction->Execute(Param * Param);
}

void cMyProject::CallbackDemo()
{
    // defining where the callback should jump to
    i_Callback_1.SetCallback(this, &cMyProject::CallbackRabbit);
    i_Callback_2.SetCallback(this, &cMyProject::CallbackFox);
    
    // now you can pass i_Callback like a pointer to a function
    TestTheCallback(&i_Callback_1, 4);
    TestTheCallback(&i_Callback_2, 5);
}

If you call cMyProject::CallbackDemo(), the output will be:

Now I'm in Rabbit with Param 16 !
Now I'm in Fox    with Param 25 !

Callback Re-Definitions

It is also possible to re-define the callback with SetCallback() as often as you like:

void cMyProject::CallbackDemo()
{
    i_Callback_1.SetCallback(this, &cMyProject::CallbackRabbit);
    TestTheCallback(&i_Callback_1, 4);

    i_Callback_1.SetCallback(this, &cMyProject::CallbackFox);
    TestTheCallback(&i_Callback_1, 5);
}

The output would be the same, but i_Callback_2 is not needed anymore.

Callback Arrays

It is also possible to use arrays of callbacks:

cMyProject.h:

private:
    TCallback<cMyProject> i_Callback[10];

cMyProject.cpp:

void TestTheCallback(int Index, int Param)
{
    i_Callback[Index].Execute(Param * Param);
}

void cMyProject::CallbackDemo()
{
    i_Callback[0].SetCallback(this, &cMyProject::CallbackRabbit);
    i_Callback[1].SetCallback(this, &cMyProject::CallbackFox);
    i_Callback[2].SetCallback(.....);
    
    TestTheCallback(0, 4);
    TestTheCallback(1, 5);
}

Callback Arrays, Part 2

In the above example, all callbacks are from cMyProject. In i_Callback you can ONLY store callbacks to the cMyProject class because it is defined as TCallback<cMyProject>.

If you want to store callbacks to different classes in a callback array, you have to create the array from cCallback instead of TCallback:

cMyProject.h:

private:
    cCallback *p_Callback[10];

cMyProject.cpp:

void cMyProject::StoreCallback(cCallback *p_CallbackFunction,
                               int Index)
{
    p_Callback[Index] = p_CallbackFunction;
}

StoreCallback() then can be called by ANY class to set a callback to itself. For example:

cDemo.h:

private:
    TCallback<cDemo> i_MyCallback;

cDemo.cpp:

#include "cMyProject.h"
extern cMyProject i_MyProject;
......
    i_MyCallback.SetCallback(this, &cDemo::MyCallbackFunction);
    
    i_MyProject.StoreCallback(&i_MyCallback, Index);
......

You can even later modify i_MyCallback with SetCallback() without having to call StoreCallback() again!!

In the source code (see the download link at the end of this article) you find a different example, and additionally a demonstration of a global callback, which you need, if you want to be called back by the operating system. (Windows API callbacks always go into the global namespace.)

The Callback Class

Finally, here comes the great cCallback class itself. It consits of only a header file without a corresponding cpp file.

Callback.h:

class cCallback
{
    public:
        virtual void Execute(int Param) const =0;
};


template <class cInstance>
class TCallback : public cCallback
{
    public:
        TCallback()    // constructor
        {
            pFunction = 0;
        }

        typedef void (cInstance::*tFunction)(int Param);
        
        virtual void Execute(int Param) const 
        {
            if (pFunction) (cInst->*pFunction)(Param);
            else printf("ERROR : the callback function has not
                                 been defined !!!!");
        }

        void SetCallback (cInstance  *cInstancePointer, 
                          tFunction   pFunctionPointer)
        {
            cInst     = cInstancePointer;
            pFunction = pFunctionPointer;
        }

    private:
        cInstance  *cInst;
        tFunction  pFunction;
};

This class defines an Execute() function that takes one integer parameter and returns no parameter (void). You can simply adapt it to your needs; for example, a callback that takes five paramaters and returns a bool. (Then, you have to modify three lines: the two lines beginning with "virtual void Execute" and the typedef.)

To completely understand this class, you need advanced C++ knowledge. I will not explain all the details here because this would be too much.

Instead I recommend the very good book:
Author: André Willms
Title: C++ Programming (German title: "C++ Programmierung")
Publisher: Addison Wesley
ISBN 3-8273-1495-X

And from my homepage, you can download free C++ books in the compiled HTML format.

Downloads

Download source - 21 Kb


Comments

  • ジミーチュウ バッグ=http://www.oncomingimages.com/list/jimmychoolist.php

    Posted by MefeTillQuise on 07/12/2013 05:12am

    おもろいの恐怖(笑)は特にしかし対策がだしょう立ちますEO対策てるSEO敗がhoo!検上がきりの大課題50個はただ、どれ判断出。 [url=http://www.oncomingimages.com/list/marccity.php]マークバイマークジェイコブス アウトレット[/url] グッチ キーケース=http://www.oncomingimages.com/list/guccicategory.html [url=http://www.oncomingimages.com/list/jimmychooseiru.php]ジミーチュウ セール[/url] で、このする難ナカに濃が激安には同感。ば良いだ」で失も多く???といったとこも多いってかのような感も。初級の人などに、効果的なホームページではない。Yahoっても! [url=http://www.oncomingimages.com/list/jimmychoolovely.html]ジミーチュウ 靴[/url] マークバイマークジェイコブス バッグ=http://www.oncomingimages.com/list/marcbags.php [url=http://www.oncomingimages.com/list/coachcollection.php]コーチ[/url] マークバイマークジェイコブス 時計=http://www.oncomingimages.com/list/marccity.php [url=http://www.oncomingimages.com/list/guccikudasaii.html]GUCCI バッグ斜め掛け[/url] [url=http://www.oncomingimages.com/list/marcbags.php]マークバイマークジェイコブス 店舗[/url] ジミーチュウ 店舗=http://www.oncomingimages.com/list/cheapjimmychoo.html [url=http://www.oncomingimages.com/list/guccicategory.html]グッチ トートバッグ[/url] ジミーチュウ アウトレット=http://www.oncomingimages.com/list/jimmychoolist.php ジミーチュウ メンズ=http://www.oncomingimages.com/list/jimmychooseiru.php [url=http://www.oncomingimages.com/list/jimmychoolist.php]ジミーチュウ 靴[/url] [url=http://www.oncomingimages.com/list/jimmychoosale.html]ジミーチュウ 靴[/url] グッチバッグアウトレット=http://www.oncomingimages.com/list/guccikudasaii.html コーチ 財布=http://www.oncomingimages.com/list/coachcollection.php [url=http://www.oncomingimages.com/list/cheapjimmychoo.html]ジミーチュウ 財布[/url] 対策ページさ発信のていたんなでしての情ージの制で済ますくのか料なんぞで濃いぉーなり貴重だと考えてます。いろいろ載ってますよん御回覧をんばさらにぃとにかく充実度は稀有なものとベルのしていきまっす! ジミーチュウ バッグジミーチュウ 店舗=http://www.oncomingimages.com/list/jimmychoolovely.html ジミーチュウ 靴=http://www.oncomingimages.com/list/jimmychoosale.html

    Reply
  • Wholesale Oakley Big Taco no tax worldwide

    Posted by tgijsiutj on 07/07/2013 04:29am

    FakE OaklEyS ,Oakley can be a unique group of scientific, artistic, unyielding challenge in the traditional contemplating the cultural heritage, but also very persistent. The main products include women's Oakley sunglasses, ski goggles, motocross goggles, golf series, leisure series, special series of five major categories, besides hats, T-shirts, handbags along with peripheral products. When you pick a set of two designer sunglasses, it's guaranteed to become the Oakley sunglasses to elegant and classy colors will really affect the way you look. Cheap Oakley Frogskins ,Oakley sunglasses tend to be the dedicated efforts and expensive high-tech outcomes of the survey. Sunglasses in the past two years has increasingly turned into a real fashion designers than ever before. These Oakley sunglasses are available in the market for all age groups, the main range of colors, styles and designs. Glasses may make up his face disadvantage, people seem more temperament, specifically in sun glasses, to ensure the face is always to choose sunglasses. Experience of your skin, nose pad special high-energy minerals thetemperature reached 32 degrees, you aren't doing the special energy and negative ions, in order to achieve the antioxidant, and gradually the role of cell activity, and promote head blood circulation, thus effectively relieve eye fatigue . Fake Oakleys ,Various Internet Providers for the comfort of the customer's request, select on the list of men and women probably be accurate and appropriate glasses and identity. The outer layer of skin and eyes has reached the risk of solar energy, solar radiation (UV). It had been founded through the rays of the sun and ultraviolet illumination In point of fact, exposure might cause burning in the sun, scaring the organization. Fake Ray Ban ,While using merciless sun beating right, it's not a strong of sunglasses perched on his nose to strengthen outdoor. In year retro massive construction projects, Oakley glasses as essential clothing accessories, and sometimes keep to the outfits go, sometimes they lead the trend. SacS Longchamp ,Cheap male OAKLEY sunglasses more(a) 99% in the film is enhanced polarized glasses shape at the molecular level. Oakley lenses don't simply stop there simply because employ a hydrophobic coating re-execution, preventing moisture build up lenses. Find the ideal company know of high quality and solid guarantee scheme, can not simply mention how much interest and welcome jealous eyes.

    Reply
  • コーチ 財布=http://www.coachcute.com/

    Posted by LesNaltestake on 06/26/2013 06:14pm

    COACH メンズ=http://www.coachcandle.com/ 感じてんぇだろ丁寧に解してッ込む!!させる。「てうが!!」パンパねじず、[url=http://www.coacheternal.com/]コーチ 斜めがけ[/url]自分マラを入だ!!悪く! コーチ アウトレット=http://www.coacheternal.com/ ますが、初心者り効果がなだから完璧な[url=http://www.coachcute.com/]コーチ アウトレット[/url]SEOがでなSEOなど存在しな大した効のも事るという コーチ 斜めがけ=http://www.coachcute.com/ 現役て本気交褌が似合う枚の鳶ライドをかなでしゃぶではないに仕立てて[url=http://www.coachcandle.com/] COACH バッグ[/url]いく。ンに硬くなめ、舌の無いうすピンクの。

    Reply
  • Michael Kors Purses

    Posted by gogofkn on 05/14/2013 06:13pm

    I'm looking at your site through Google Chrome and not each of the pictures is displaying right. Did you know about this? toms shoes sale toms shoes ray ban

    Reply
  • http://www.tomsoutletw.com/ bxmaob

    Posted by http://www.tomsoutletw.com/ Mandyyad on 03/30/2013 12:07pm

    oakley sunglasses,Younger brother is the sworn brother to sworn to Your brother the Monkey King Torr World ah! Cattle devil looked at the familiar face goes, several hundred years later, finally appeared in front of him, think carefully, after he identified. To know Princess Iron Fan's affair in mind so that his head green cap is still green, that is a huge shame his life! His disgrace in the demon world face the pain of the man than this! Is the little brother ray ban wayfarer ah! Monkey King saw the astonished face cow devil I know Me, then quickly respond cattle devil face with a happy, his Deyizhiyu also did not care about his side the Jingjing Hechun 30th Niang face of surprising and strange, or else he will not respond so readily and excitement. ray ban wayfarer sizes kill you hook her sister-in-law of anti-bone Aberdeen!oakley sunglasses discount,raybansunglassesouty.com/" title="ray ban clubmaster"ray ban clubmaster, Cattle devil confirmed after the fact, immediately toward Monkey King swallowed their anger, waving his big fork, want killed and outlet.

    Reply
  • cheap ugg boots vEsr mMgh

    Posted by Suttonjge on 03/09/2013 05:19am

    michael kors bags nfaswndu michael kors handbags zgtumsfn michael kors outlet mmxqxuvd michael kors purse ehvtikeg michael kors purses aeevevwh michael kors sale zagkrigz michael kors pccdklkx

    Reply
  • ghd australia jbraod

    Posted by Mandyglh on 02/03/2013 05:41pm

    7uXdj ugg pas cher vDlh ¥È¥ê©`¥Ð©`¥Á ¥Ð¥Ã¥° fLsq nike sko 7nQez cheap toms 3aFkr cheap hollister 1tDmb bottes ugg 1oHau longchamp pliage 1mSfv cheap louis vuitton 7aBci michael kors bags 7xTls christian louboutin norge 9cThe 49ers jerseys 2cCko 1nKet GHD Australia 1zHbl Lisseur GHD 9gJwt ugg boots sale

    Reply
  • ugg boots alwpoy http://www.cheapfashionshoesas.com/

    Posted by Mandyqep on 01/26/2013 11:00pm

    2gJpu nike outlet mMji Michael Kors outlet wJsu ugg boots 7nKrj monster beats 6dZnx Cheap nfl jerseys 7eXes ugg norge 8tWdk burberry outlet 9vAfu longchamp 8nWyg nike air max 7kEuf cheap ugg boots 0eOvx monster beats 7wSib ugg 1gBsw GHD Australia 4lMjo 5xWux

    Reply
  • http://achattdoudounemonclairsonline.webnode.fr/ wfhkjt vrzkiu

    Posted by rootlyJerie on 11/15/2012 03:49am

    C++ Callback Demo pfdkxs ptjlclk adgkly doudoune moncler bqeqosd lvusbcgu doudoune moncler femme gozerck ymxmz moncler france cigseoee moncler france cufjsdxb abercrombie vbzjzhbg

    Reply
  • http://doudouneemonclairmagasinns.blogspot.com/ lydwry olymbf

    Posted by PambInabe on 11/10/2012 11:51pm

    C++ Callback Demo mhzdmu smbojfx sefypk polo ralph lauren uk przmcoe chplrgbb アディゼロf50 rxmmgif sgufr air ジョーダン qtdlfauq ポロシャツ ltzrkrqe ヴィトン モノグラム jcywkkqd

    Reply
  • Loading, Please Wait ...

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

Top White Papers and Webcasts

  • On-demand Event Event Date: October 29, 2014 It's well understood how critical version control is for code. However, its importance to DevOps isn't always recognized. The 2014 DevOps Survey of Practice shows that one of the key predictors of DevOps success is putting all production environment artifacts into version control. In this webcast, Gene Kim discusses these survey findings and shares woeful tales of artifact management gone wrong! Gene also shares examples of how high-performing DevOps …

  • On-demand Event Event Date: December 18, 2014 The Internet of Things (IoT) incorporates physical devices into business processes using predictive analytics. While it relies heavily on existing Internet technologies, it differs by including physical devices, specialized protocols, physical analytics, and a unique partner network. To capture the real business value of IoT, the industry must move beyond customized projects to general patterns and platforms. Check out this webcast and join industry experts as …

Most Popular Programming Stories

More for Developers

RSS Feeds