P/Invoke with SafeHandle as reference parameter

463 Views Asked by At

I have a Function in an unmanaged Dll which expects a pointer to a Handle like that example:

extern "C" __declspec(dllexport) BOOL __stdcall MySetEvent(HANDLE* handle, 
int size)
{
    if (!handle) return FALSE;
    assert(sizeof(*handle) == size);
    printf("MySetEvent(%p, %d)\n", *handle, size);
    return SetEvent(*handle);
}

How I can call this from C# without using DangerousGetHandle like in that example?

[DllImport("UnmanagedDll", SetLastError = true)]
static extern int MySetEvent(ref IntPtr handle, int size);


AutoResetEvent ev = new AutoResetEvent(false);
var handle = ev.SafeWaitHandle.DangerousGetHandle();
MySetEvent(ref handle, Marshal.SizeOf(handle));

This doesn't work (a MissingMethodException for .ctor is thrown):

[DllImport("UnmanagedDll", SetLastError = true)]
static extern int MySetEvent([In] ref SafeHandle handle, int size);


SafeHandle handle = ev.SafeWaitHandle;
MySetEvent(ref handle,  Marshal.SizeOf(IntPtr.Zero));
0

There are 0 best solutions below