Click here to Skip to main content
15,306,369 members
Articles / Programming Languages / C++/CLI
Posted 13 Jul 2002


37 bookmarked

Implementing Callback functions using IJW (avoiding DllImport)

Rate me:
Please Sign up or sign in to vote.
4.53/5 (16 votes)
13 Jul 20024 min read
Shows how you can call native API functions that require callbacks using IJW, and without the use of DllImport attribute. The technique allows you to pass a delegate as the callback function just as in the MS recommended manner except, I show you how to do this without the ugly DllImport attribute.

Image 1


This whole business started one day when there was a post in the Microsoft newsgroup where someone was complaining that he was having trouble using EnumWindows from Managed C++. He stated very firmly that he did not want to use the DllImport attribute. This got me interested naturally, and I thought I could try and help him out. To my utter disappointment I found that I was having trouble too. The issue was that EnumWindows took as it's first argument a callback function. All my searches on MSDN and google took me to solutions that showed how to do this using the DllImport attribute. The technique suggested was simple. We are to declare a __delegate object identical to the callback function. Now we are to use DllImport to define EnumWindows so that it takes as first argument our

type. Now we can simply write our callback function as a member of a managed class and pass this function to EnumWindows.

//declare our delegate
__delegate bool CallBack(IntPtr hwnd, IntPtr lParam);


//ugghhhhhhh!!!! so uglyyyyyy!!!
extern "C" int EnumWindows(CallBack* x, int y); 


//create the delegate
CallBack* cb = new CallBack(0, 
//call the function
EnumWindows(cb, 0); 

The problem

All this is well and good, but it was beginning to get annoying. My problem was that whatever I did I couldn't get the callback function to work. Obviously I couldn't pass a delegate directly because when we use IJW, the native API functions expect native arguments and not managed arguments. I even tried something as silly as casting a delegate object to a WNDENUMPROC and as you might have guessed failed thoroughly. I also tried passing both static and instance members of managed classes as the callback function, but I kept getting run time exceptions about NULL references and objects. This was really disappointing to say the least.

That's when I got a huge boost from Richard Grimes who is a Microsoft MVP, and who has written several quality books on Microsoft programming technologies. His latest book is on using the managed extensions to program with VC++ .NET. In reply to my query about calling EnumWindows using IJW, he replied to me and the reply included a sample code snippet from his latest book, but unfortunately he used DllImport. I replied back saying that I wasn't looking for DllImport and I must say my exasperation must have reflected poorly in my reply. Because Richard's answer was a little crispy too to begin with. But he gave me my first clue as to why I was going the wrong direction. He explained to me how managed class members use the __clrcall calling convention and how unmanaged callback functions use the __stdcall calling convention  In fact when I took a closer look at the compiler warnings, I was shocked to find a message that said that I was trying to attempt a redefinition of calling convention from __clrcall to __stdcall  which is not possible and was therefore being ignored. That's when I realized that I simply had to give up trying to use a managed class member method as my callback.

The solution

Richard's final answer was an emphatic NO. But I badly wanted to figure out a way by which a managed class can pass a delegate as the callback function. That's when this idea hit me out of the blue. Inner classes. We could use inner classes, see! All we had to do was to have an __gc class with an inner __nogc class and the outside managed class will wrap the inner unmanaged class and expose it to the outside world. The outer class has a delegate that acts as the managed callback. The inner __nogc class has a native __stdcall method as the callback function. This callback function will invoke the managed delegate each time it gets called. Thus we simulate a managed callback mechanism here. I have commented the code in vital areas so that you can understand this better.

__gc class CEnumWindows //outer class
    __nogc class _CEnumWindows //inner class
        /* This is a native function that follows the */
        /* __stdcall calling convention that's required */
        static  BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM)
            // We need to get the managed callback
            // up for each instance that our callback 
            // gets called. So we get a pointer to
            // the current instance of the outer class
            // and invoke the delegate that is holding
            // the managed callback method that the
            // callee code has passed to us
            CEnumWindows* pew = CEnumWindows::GetClass();
            pew->m_EnumProc->Invoke(hwnd, NULL);
            return TRUE;
        void StartFinding()
    _CEnumWindows* m_ew;
    __delegate bool EnumProc(IntPtr hwnd, IntPtr lParam);
    static CEnumWindows* GetClass()
        //This for the unmanaged class to use
        //when it needs a pointer to the managed class
        return m_pclass;        
    static CEnumWindows* m_pclass=NULL;
        m_pclass = this;
        m_ew = new _CEnumWindows(); //unmanaged heap
        // we need to delete the object manually
        // as is is on the unmanaged heap
        delete m_ew;
    void StartFinding()
    EnumProc* m_EnumProc;

Now we can use this from any managed class and pass any managed class member function as the callback function. In the example below, I create a new instance of CEnumWindows which is the outer class. Then I associate a managed function from one of my classes to the delegate member of the CEnumWindows object. Alright, alright, I know that using a public delegate member is not a proper way to do this, but I am only trying to demonstrate how this is done. Put this in a property if you want to, or write a function that'll do this for you.

CEnumWindows* p = new CEnumWindows();
p->m_EnumProc = new CEnumWindows::EnumProc(this,&NForm::EWHandler);


For my own whimsical reasons I am a big fan of using IJW which I feel is a lot more natural for a C++ programmer than the use of weird looking attributes that makes your code look like C# or VB .NET. I don't have anything against other languages but I prefer my C++ code too look like C++ and not like some kind of ugly mutation of other subjectively inferior languages. Anyway thanks goes to Richard Grimes for pointing me in the correct direction. Those of you who are interested in his new book on using the managed extensions can go to this link. Programming with Managed Extensions for Microsoft® Visual C++® .NET (Microsoft Press)


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Nish Nishant
United States United States
Nish Nishant is a Principal Software Architect based out of Columbus, Ohio. He has over 17 years of software industry experience in various roles including Lead Software Architect, Principal Software Engineer, and Product Manager. Nish was a Microsoft Visual C++ MVP between 2002 and 2015.

Nish is an industry acknowledged expert in the Microsoft technology stack. He authored C++/CLI in Action for Manning Publications in 2005, and had previously co-authored Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on and another 250+ blog articles on his WordPress blog. Nish is vastly experienced in team management, mentoring teams, and directing all stages of software development.

Contact Nish : If you are interested in hiring Nish as a consultant, you can reach him via his google email id voidnish.

Company Website :

Comments and Discussions

GeneralCalling managed code from MFC Pin
Lithium0220-Dec-10 13:30
MemberLithium0220-Dec-10 13:30 
GeneralNice Trick but Confusing Code !!! Pin
Vivek Ragunathan19-Mar-08 19:17
MemberVivek Ragunathan19-Mar-08 19:17 
GeneralMixed Mode to the rescue! Pin
villalvilla5-May-06 0:55
Membervillalvilla5-May-06 0:55 
QuestionWhy? Pin
hanifku9-Apr-06 14:02
Memberhanifku9-Apr-06 14:02 
AnswerRe: Why? Pin
PunCha20-Nov-06 15:21
MemberPunCha20-Nov-06 15:21 
GeneralConverting the sample to remove the singleton Pin
Nigel de Costa4-Apr-05 5:11
MemberNigel de Costa4-Apr-05 5:11 
GeneralConverting the sample to use managed events... Pin
Nigel de Costa3-Apr-05 22:48
MemberNigel de Costa3-Apr-05 22:48 
GeneralLNK2001: unresolved external symbol "void * __cdecl operator new(unsigned int)" (??2@$$FYAPAXI@Z) Pin
markbanderson29-Jan-04 10:55
Membermarkbanderson29-Jan-04 10:55 
GeneralRe: LNK2001: unresolved external symbol "void * __cdecl operator new(unsigned int)" (??2@$$FYAPAXI@Z) Pin
markbanderson30-Jan-04 0:11
Membermarkbanderson30-Jan-04 0:11 
GeneralRe: LNK2001: unresolved external symbol "void * __cdecl operator new(unsigned int)" (??2@$$FYAPAXI@Z) Pin
Sudesh Sawant15-Mar-05 18:34
sussSudesh Sawant15-Mar-05 18:34 
GeneralRe: LNK2001: unresolved external symbol "void * __cdecl operator new(unsigned int)" (??2@$$FYAPAXI@Z) Pin
Denis Delarze7-May-04 6:12
sussDenis Delarze7-May-04 6:12 
Generalpassing pointers from unmanaged to managed Pin
Reza Shademani8-Oct-03 6:44
MemberReza Shademani8-Oct-03 6:44 
GeneralConfused Pin
igor196023-Sep-03 7:58
Memberigor196023-Sep-03 7:58 
QuestionHow to invoke the delegate asynchronously ? Pin
Yoni Rabinovitch11-Sep-03 2:27
MemberYoni Rabinovitch11-Sep-03 2:27 
AnswerRe: How to invoke the delegate asynchronously ? Pin
BumblebeeFromNewYork3-Nov-03 6:31
MemberBumblebeeFromNewYork3-Nov-03 6:31 
GeneralRe: How to invoke the delegate asynchronously ? Pin
Yoni Rabinovitch3-Nov-03 18:44
MemberYoni Rabinovitch3-Nov-03 18:44 
GeneralRight way Pin
Rama Krishna Vavilala27-Jul-02 3:45
MemberRama Krishna Vavilala27-Jul-02 3:45 
GeneralRe: Right way Pin
567890123414-Apr-03 22:39
Member567890123414-Apr-03 22:39 
GeneralAnother solution Pin
Daniel Lohmann15-Jul-02 7:15
MemberDaniel Lohmann15-Jul-02 7:15 
GeneralRe: Another solution Pin
Nish Nishant15-Jul-02 13:54
sitebuilderNish Nishant15-Jul-02 13:54 
GeneralRe: Another solution Pin
PVL23-Jun-03 8:16
MemberPVL23-Jun-03 8:16 
GeneralGood work Pin
Kannan Kalyanaraman14-Jul-02 21:52
MemberKannan Kalyanaraman14-Jul-02 21:52 
GeneralRe: Good work Pin
Nish Nishant15-Jul-02 13:51
sitebuilderNish Nishant15-Jul-02 13:51 
GeneralNot thread safe Pin
Rama Krishna Vavilala14-Jul-02 2:27
MemberRama Krishna Vavilala14-Jul-02 2:27 
GeneralRe: Not intended to be so Pin
Nish Nishant14-Jul-02 3:32
sitebuilderNish Nishant14-Jul-02 3:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.