开发者

convert a class type object to Intptr

开发者 https://www.devze.com 2023-02-13 08:32 出处:网络
helo I know this may be easy but believe me I didn\'t understud it from what I found on google. I trying to do the folowing thi开发者_运维百科ng :

helo I know this may be easy but believe me I didn't understud it from what I found on google. I trying to do the folowing thi开发者_运维百科ng :

unsafe static IntPtr __convertSearcherCallbackParameterToIntPtr (SearcherCallbackParameter searcherCallbackParameter ) { return (*(IntPtr*)&searcherCallbackParameter); }

where SearcherCallbackParameter is a class and I need to convert it to an IntPtr so I can pass it as a parameter to a windows api.

I get the folowing error: Cannot take the address of, get the size of, or declare a pointer to a managed type


You can just use a simple .NET delegate, the interop layer will take care of the marshalling. The following code takes the native function declarations from http://pinvoke.net/default.aspx/user32/EnumWindows.html

The callback function parameter is just an integer though so it doesn't actually have to be an IntPtr.

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


[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool EnumWindows(CallBackPtr lpEnumFunc, UInt32 lParam);


static bool callbackreport(int hwnd, int lparam)
{
    Console.WriteLine("{0} {1}", hwnd, lparam);
    return true;
}

static void Main(string[] args)
{
    EnumWindows(Program.callbackreport,0);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消