0

Context: My situation is that I have to use an externally written native library from a managed .net environment. This native library sends messages realtime to my application at small intervals. It is expected from my application to respond within a certain amount of time. When this requirement is not met the situation is recoverable, but it does make the application slow for the user. There were many reaction speed issues which were all solved by adding an AutoResetEvent event in combination with a thread waiting for it.

The problem: The libary exposes a method through which I can pass a pointer to a handle from an AutoResetEvent. I pass this handle as an uint.

var handle = resetEvent.SafeWaitHandle.DangerousGetHandle();
var pointer = (uint)handle.ToInt32();
SetParameterValue(channel, param, pointer, 4); 

And this handle is passed to the following method:

[DllImport("PCANBasic.dll", EntryPoint = "CAN_SetValue")]
private static extern NativeCanStatus SetParameterValue(
        ushort Channel,
        byte Parameter,
        uint Handle,
        uint BufferLength);

Everything seems to work great. However I did just write some code I do not understand the internal workings of. The name DangerousGetHandle is not really assuring. When the application is closed I set the parameter to a null-pointer, however I can not guarantee in the event of an application crash that I will set this paramater to a null-pointer. It seems to not cause any issues, but I do not understand why it doesn't give me any issues.

So, how unsafe is passing the DangerousHandle of an AutoResetEvent to a native library? Can the native library after an application failure keep calling something at this pointer? Or is this perfectly fine?

Bart
  • 547
  • 2
  • 12
  • 1
    It is just a reminder that it is entirely up to you to ensure that the AutoResetEvent object cannot be garbage-collected as long as the native code is using that handle. There is nothing the CLR or the framework can do to take care of that for you. Consider declaring the variable as *static*. – Hans Passant Aug 28 '18 at 15:35
  • 1
    `DangerousGetHandle` is fine but the code only works in 32-bit builds. In 64-bit builds handle values are 64 bits. You should be using `IntPtr` in C#, and `HANDLE` or `void*` in the API of that native library. – Soonts Aug 28 '18 at 15:55

0 Answers0