ME.
ME.

Reputation: 1

addressof-operator in c#

In a winapi function I have to pass the address of the callback function that function has to use.

So I declared a unsafe class and everything, but bool* addressofmyfunction = &GetHandle; just won't compile!

Please help me or give me an alternative to passing the address like this.

Upvotes: 0

Views: 920

Answers (3)

dtb
dtb

Reputation: 217313

Function pointers are represented by delegates in C#. Since methods aren't moved by the garbage collector, you don't need to pin them (or use unsafe code) to pass them to a Win32 API function.

Example:

using System;
using System.Runtime.InteropServices;

public delegate bool CallBack(int hwnd, int lParam);

public class EnumReportApp {

    [DllImport("user32")]
    public static extern int EnumWindows(CallBack x, int y); 

    public static void Main() 
    {
        CallBack myCallBack = new CallBack(EnumReportApp.Report);
        EnumWindows(myCallBack, 0);
    }

   public static bool Report(int hwnd, int lParam) { 
        Console.Write("Window handle is ");
        Console.WriteLine(hwnd);
        return true;
    }
}

There is a similar example for EnumThreadWindows on pinvoke.net.

Upvotes: 2

erikkallen
erikkallen

Reputation: 34401

bool* addressofmyfunction = &GetHandle won't compile in C or C++ either (the correct syntax would be bool (*addressofmyfunction)() = &GetHandle), but you can't do like that. I'm not an expert in interop, but I think you have to use Marshal.GetFunctionPointerForDelegate.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038890

In .NET delegates are used to store pointers to functions. For example if you have the following function:

public int GetHandle(int arg1)
{ 
    return arg1 + 10;
}

it's address will be defined like so:

Func<int, int> addressOfMyFunction = GetHandle;

and you can invoke it like that:

int result = addressOfMyFunction(50);

Upvotes: 5

Related Questions