简体   繁体   中英

convert a class type object to Intptr

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 thing :

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM