How does .NET runtime convert SafeHandle to IntPtr and vice versa?

279 Views Asked by At

I have a C++ function that accepts a pointer to a native object. I can call the function from my C# code in two ways:

  1. Pass an IntPtr to it, like this,
  2. Pass the subclass of the SafeHandle to it, like this.

While the first case is quite straightforward, I'm struggling to understand what is actually happening under the hood in the second case.

Does the runtime simply call DangerousGetHandle() on the SafeHandle? Does it also update the reference counter on the SafeHandle instance using DangerousAddRef() and DangerousRelease(), by analogy with SafeBuffer.AcquirePointer()?

The reason I'm trying to understand this is that I have an old native API that can only accept IntPtr, there is no way to use the implicit SafeHandle to IntPtr conversion, so I'm wondering weather it would be acceptable to manually "convert" SafeHandle to IntPtr using DangerousGetHandle().

I tried to decompile the DLL with my C# code hoping to see what is happening during the conversion, however, it seems like the conversion is not a part of the DLL, the code seems to be a part of the runtime.

0

There are 0 best solutions below