0

我在非托管 Dll 中有一个函数,它需要一个指向句柄的指针,如该示例:

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

0 回答 0