0

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));
AndiR
  • 179
  • 10
  • Fix the C++ code, the argument needs to be HANDLE, not HANDLE*. And do consider that it doesn't do anything different from AutoResetEvent.Set(), there is no conceivable advantage to calling SetEvent(). – Hans Passant May 03 '18 at 08:54
  • The C Code is third party and does a little bit more. The Code above is only an exmple for explaining the issue. – AndiR May 03 '18 at 08:56
  • "this doesn't work" does not explain anything. – Hans Passant May 03 '18 at 09:00
  • Looks to me like `DangerousGetHandle` is exactly what you need. Yes, it has "dangerous" in the name, but that's because you're doing a dangerous thing. That function is not "sane", and has no need for eating pointers to handles, while a function that has a genuine need for that probably couldn't be called safely from managed code (because it wants to hang on to the pointer or change it). If you want to "safely" use `DangerousGetHandle`, either read up on how to use `DangerousAddRef`/`Release` or write some C++/CLI code to provide better glue between C# and the unmanaged DLL. – Jeroen Mostert May 03 '18 at 09:29

0 Answers0