Click here to Skip to main content
15,861,125 members
Articles / Programming Languages / C++/CLI
Article

Function pointers and Delegates - Closing the gap!

Rate me:
Please Sign up or sign in to vote.
4.55/5 (24 votes)
17 Jun 2005Ms-PL4 min read 164.7K   44   29
Explains the usage of the Marshal class methods GetFunctionPointerForDelegate and GetDelegateForFunctionPointer, and compares their performance with the P/Invoke mechanism.

Introduction

3 years ago, I had written an article titled Implementing Callback functions using IJW (avoiding DllImport) that described a technique by which you could call API functions requiring callbacks without using the DllImport mechanism. The technique I used involved declaring an __gc class with an inner __nogc class with the __gc class wrapping the inner class and exposing a managed interface to the outer world. While it was rather contorted a technique, it was the only option at that time. But today, with the release of Whidbey around the corner, things have got a whole lot better, with the introduction of two new methods in the Marshal class - GetFunctionPointerForDelegate and GetDelegateForFunctionPointer. Now you can take a function pointer and wrap a delegate around it, or the reverse - take a delegate and use it as a function pointer. This article demonstrates both techniques using the almost proverbial EnumWindows example everyone uses when they want to demonstrate something to do with callback functions.

Sample usage

MC++
delegate BOOL EnumWindowsDelegateProc(HWND hwnd,LPARAM lParam);

I've declared the delegate type that'll be exposed to the .NET world (or at least to the C++ .NET world given that I've used some native types). The delegate type matches the callback prototype for the EnumWindows function

MC++
ref class WindowEnumerator
{
private:
    EnumWindowsDelegateProc^ _WindowFound;
public:
    WindowEnumerator()
    {
        _WindowFound = nullptr;
    }
    event EnumWindowsDelegateProc^ WindowFound
    {
    public:
        void add(EnumWindowsDelegateProc^ d)
        {
            if(_WindowFound == nullptr)
                _WindowFound = d;                
        }
        void remove(EnumWindowsDelegateProc^)
        {            
            _WindowFound = nullptr;
        }
    }
    void Init()
    {
        pin_ptr<EnumWindowsDelegateProc^> tmp =  &_WindowFound;
        EnumWindows((WNDENUMPROC)Marshal::GetFunctionPointerForDelegate(
            _WindowFound).ToPointer(), 0);        
    }
};

I have a non-trivial event (WindowFound) that's of the delegate type declared earlier - the reason I had to use a non-trivial event is that C++/CLI does not treat an event as a regular class member and won't allow operations like & (address of) on an event member. Notice how I check for nullptr before assigning the event handler - this is done to ensure that there is only one delegate associated with the event. The crux of the code is in the Init method where I've called EnumWindows directly and have used GetFunctionPointerForDelegate to convert the delegate object into a function pointer. If you look at the mscorlib source using Reflector or ILDasm, you'll see that

MC++
GetFunctionPointerForDelegate
does a nullptr check and then calls an extern function
MC++
GetFunctionPointerForDelegateInternal
.
MC++
GetFunctionPointerForDelegateInternal
creates a native callable stub around the delegate that has been passed in and my best guess as to where it's defined in would be mscorwks.dll (just a guess, someone who works in the CLR team will know better). Notice how I pin the delegate object using a temporary pin_ptr variable, this is because I do not want the delegate object to be moved around on the CLR heap while I am using the function pointer in native code.

MC++
delegate int DispProc(String^, String^);

Here, I've declared my second delegate (which I'll use to wrap the

MC++
printf
function provided in the CRT library).

MC++
ref class MyClass
{
public:
    static BOOL HandleFoundWindow(HWND hwnd,LPARAM lParam)
    {
        char buff[512];
        GetWindowText(hwnd, buff, 511);
        if(IsWindowVisible(hwnd) && pDispProc && strlen(buff))
            pDispProc("%s\r\n",gcnew String(buff));
        return TRUE;
    }
    static DispProc^ pDispProc =  nullptr;
};

This class simply defines a static HandleFoundWindow method that matches the delegate prototype expected by the

MC++
WindowEnumerator
class. Notice that I could have used
MC++
Console::WriteLine
here, but I wanted to use a delegate that wrapped a function pointer (so I could demonstrate the use of the
MC++
GetDelegateForFunctionPointer
method. After having written so many articles and a technical book, I've lost any traces of shame when I invent unusually contorted examples to demonstrate coding techniques. Many others like me who do technical authoring are notorious for creating the most beautiful pieces of code that'll never ever serve any purpose in a real-world production environment. So, kindly have mercy on me guys.

MC++
int main(array<System::String ^> ^args)
{
    WindowEnumerator wenum;
    EnumWindowsDelegateProc^ d1 = gcnew EnumWindowsDelegateProc(
        MyClass::HandleFoundWindow);
        
    wenum.WindowFound += d1;        
    
    HMODULE h1 = LoadLibrary("msvcrt.dll");
    if(h1)
    {
        typedef int (*FUNC_PTR)(const char *, ...); 
        FUNC_PTR pfn = reinterpret_cast<FUNC_PTR>(GetProcAddress(h1, "printf"));
        if(pfn)
        {
            DispProc^ d2 = (DispProc^)Marshal::GetDelegateForFunctionPointer(
                (IntPtr)pfn,DispProc::typeid);
            MyClass::pDispProc = d2;
            wenum.Init();
        }
        
        FreeLibrary(h1);
    }
    
    return 0;
}

I get a pointer to the printf function using LoadLibrary/GetProcAddress and call GetDelegateForFunctionPointer to create a delegate that wraps this function pointer. If you look at the implementation of

MC++
GetDelegateForFunctionPointer
, you'll see that it does some nullptr checks, then checks to see that you've actually passed in a Delegate type and then calls an extern function
MC++
GetDelegateForFunctionPointerInternal
.
MC++
GetDelegateForFunctionPointerInternal
creates a new delegate that wraps a native function pointer (similar to the P/Invoke mechanism) and is defined in an undocumented DLL - my best guess, as I mentioned earlier is mscorwks.dll, but I might be wrong there. MSDN says that the function pointer that's passed must be a pure unmanaged function pointer - means you cannot safely pass in a native pointer in a mixed-mode module. Though when I tested it with a local function in a mixed-mode project, things worked pretty smooth - but it's safer to follow MSDN guidelines - you never know when something'll break otherwise.

Performance improvement

I did a little speed test to see which is more performant. I wrote two classes - both of them enumerating windows using the EnumWindows API, one of which used P/Invoke while the other used the

MC++
Marshal::GetFunctionPointerForDelegate
method to manually do the delegate to function pointer conversion. Just as I expected, the latter method was more efficient and this efficiency improvement was seen to be pretty consistent as I increased the iterations.

Here are the two classes :-

MC++
delegate int DEnumWindowsProc(IntPtr hWnd, IntPtr lParam);

ref class Base abstract
{
public:
    static int EnumWindowsProc(IntPtr hWnd, IntPtr lParam)
    {
        return TRUE;
    }
    virtual void Init() abstract;
};

ref class PIClass : Base
{
public:
    [DllImport("user32.dll")]
    static bool EnumWindows(DEnumWindowsProc^ lpEnumFunc, 
        IntPtr lParam);

    virtual void Init() override
    {
        EnumWindows(gcnew DEnumWindowsProc(EnumWindowsProc), 
            IntPtr::Zero);        
    }

};

ref class FuncPtrClass : Base
{
public:
    static DEnumWindowsProc^ dg = gcnew DEnumWindowsProc(EnumWindowsProc);

    virtual void Init() override
    {
        pin_ptr<DEnumWindowsProc^> tmp =  &dg;
        ::EnumWindows((WNDENUMPROC)
            Marshal::GetFunctionPointerForDelegate(dg).ToPointer(), 0);            
    }
};

And here's my test code :-

MC++
generic<typename T> where T : Base int CalcSpeed(int count)
{    
    Console::WriteLine(
        "Checking class : {0} with {1} iterations", T::typeid, count);
    T t = Activator::CreateInstance<T>();        
    DWORD start = GetTickCount();
    while(count--)
        t->Init();
    DWORD stop = GetTickCount();
    Console::WriteLine("{0} milliseconds", stop - start);
    return stop - start;
}

void DoCalc(int count)
{
    int t1 = CalcSpeed<PIClass^>(count);
    int t2 = CalcSpeed<FuncPtrClass^>(count);
    float pc = (float)(t1-t2)/t1 * 100;
    int pcrounded = (int)pc;
    Console::WriteLine(
        "{0}% improvement for {1} iterations\r\n", pc, count);
}

int main(array<System::String ^> ^args)
{    
    DoCalc(10000);
    DoCalc(50000);
    DoCalc(100000);
    DoCalc(500000);
    return 0;
}

Here's the output I got (you'll get slightly varying results obviously) :-

Image 1

History

  • June 17, 2005 : Article first published.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
United States United States
Nish Nishant is a technology enthusiast from Columbus, Ohio. He has over 20 years of software industry experience in various roles including Chief Technology Officer, Senior Solution Architect, Lead Software Architect, Principal Software Engineer, and Engineering/Architecture Team Leader. Nish is a 14-time recipient of the Microsoft Visual C++ MVP Award.

Nish authored C++/CLI in Action for Manning Publications in 2005, and co-authored Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his WordPress blog. Nish is experienced in technology leadership, solution architecture, software architecture, cloud development (AWS and Azure), REST services, software engineering best practices, CI/CD, mentoring, and directing all stages of software development.

Nish's Technology Blog : voidnish.wordpress.com

Comments and Discussions

 
News[My vote of 1] how do I pass pass a method adress from win32 application to c# library method which has Action as a parameter Pin
a ahole26-Jun-11 5:37
a ahole26-Jun-11 5:37 
Questionhow do I pass pass a method adress from win32 application to c# library method which has Action as a parameter Pin
a ahole26-Jun-11 5:19
a ahole26-Jun-11 5:19 
GeneralMore comment: can't cast IntPtr directly to function pointer Pin
dtr2228-Oct-08 1:53
dtr2228-Oct-08 1:53 
QuestionHow about translating it to the managed world? Pin
donnythebowler18-Oct-06 8:38
donnythebowler18-Oct-06 8:38 
GeneralTrivial Event woes Pin
tonyt28-Sep-06 4:19
tonyt28-Sep-06 4:19 
GeneralPinning unnecessart (I think...) Pin
A Debaene30-Aug-06 1:42
A Debaene30-Aug-06 1:42 
GeneralRe: Pinning unnecessart (I think...) Pin
Nish Nishant30-Aug-06 2:00
sitebuilderNish Nishant30-Aug-06 2:00 
Generalpin_ptr Pin
philipp__p10-Jul-06 5:12
philipp__p10-Jul-06 5:12 
Hi,

I really appreciate this article but lets consider the use of pin_ptr.

As pin_ptr are stored on the stack rather then in the heap I assume that it looses its function after the scope of the init method.
At the time the callback is triggered it wont protect the address of the delegate any more.

Do I assume wright? Please give me some advice concerning pin_ptr.

Thanks.

Phil
GeneralFunction pointers Pin
Parag Gadkari23-May-06 5:57
Parag Gadkari23-May-06 5:57 
Questionpointer to member functions?? Pin
TheLion4-May-06 9:51
TheLion4-May-06 9:51 
AnswerRe: pointer to member functions?? Pin
Sameer Khan29-Oct-07 7:32
Sameer Khan29-Oct-07 7:32 
GeneralRe: pointer to member functions?? Pin
TheLion29-Oct-07 8:01
TheLion29-Oct-07 8:01 
GeneralRe: pointer to member functions?? Pin
Sameer Khan30-Oct-07 4:47
Sameer Khan30-Oct-07 4:47 
QuestionC# example? Pin
Calibus_22-Feb-06 3:40
Calibus_22-Feb-06 3:40 
AnswerRe: C# example? Pin
Nish Nishant22-Feb-06 3:51
sitebuilderNish Nishant22-Feb-06 3:51 
GeneralRe: C# example? Pin
Calibus_22-Feb-06 5:09
Calibus_22-Feb-06 5:09 
GeneralRe: C# example? Pin
M i s t e r L i s t e r24-Mar-06 8:05
M i s t e r L i s t e r24-Mar-06 8:05 
QuestionVS 2005 solution? Pin
ericwilliamg8-Nov-05 11:39
ericwilliamg8-Nov-05 11:39 
AnswerRe: VS 2005 solution? Pin
ericwilliamg8-Nov-05 11:54
ericwilliamg8-Nov-05 11:54 
Question^ accent usage ? Pin
toxcct23-Jun-05 1:50
toxcct23-Jun-05 1:50 
AnswerRe: ^ accent usage ? Pin
Nish Nishant23-Jun-05 1:56
sitebuilderNish Nishant23-Jun-05 1:56 
GeneralRe: ^ accent usage ? Pin
toxcct23-Jun-05 5:20
toxcct23-Jun-05 5:20 
GeneralRe: ^ accent usage ? Pin
Nish Nishant24-Jun-05 2:04
sitebuilderNish Nishant24-Jun-05 2:04 
GeneralInitialization lists Pin
Nemanja Trifunovic17-Jun-05 9:54
Nemanja Trifunovic17-Jun-05 9:54 
GeneralRe: Initialization lists Pin
Nish Nishant17-Jun-05 18:11
sitebuilderNish Nishant17-Jun-05 18:11 

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.