P / Invoke with SafeHandle作为参考参数

时间:2018-05-03 08:41:02

标签: c# pinvoke ref safehandle

我在一个非托管的Dll中有一个函数,它需要一个像Handle那样的指针:

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

如何在不使用DangerousGetHandle的情况下从C#调用此方法?

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

这不起作用(抛出.ctor的MissingMethodException):

[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 个答案:

没有答案