Why is SafeHandle.DangerousGetHandle () "Dangerous"?

This is the first time I use SafeHandle.

I need to call this P / Invoke method which needs UIntPtr.

    [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
    public static extern int RegOpenKeyEx(
      UIntPtr hKey,
      string subKey,
      int ulOptions,
      int samDesired,
      out UIntPtr hkResult);

This UIntPtr will be retrieved from the .NET RegistryKey class. I will use the method above to convert the RegistryKey class to IntPtr, so I can use the above P / Invoke:

        private static IntPtr GetRegistryKeyHandle(RegistryKey rKey)
        {
            //Get the type of the RegistryKey
            Type registryKeyType = typeof(RegistryKey);

            //Get the FieldInfo of the 'hkey' member of RegistryKey
            System.Reflection.FieldInfo fieldInfo =
                registryKeyType.GetField("hkey", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            //Get the handle held by hkey
            if (fieldInfo != null)
            {
                SafeHandle handle = (SafeHandle)fieldInfo.GetValue(rKey);

                //Get the unsafe handle
                IntPtr dangerousHandle = handle.DangerousGetHandle();                
                return dangerousHandle;
            }
}

Questions:

  • Is there a better way to write this without using "unsafe" descriptors?
  • Why are dangerous pens dangerous?
+5
source share
2 answers

, , . RegistryKey, , , IntPtr. , . , , - , , . , - .

:

[DllImport("advapi32.dll", CharSet=CharSet.Auto)]
internal static extern int RegOpenKeyEx(SafeRegistryHandle key, string subkey, 
    int options, int sam, out SafeRegistryHandle result);

, safe handle. .

+3

RegistryKey handle. ,

private static IntPtr GetRegistryKeyHandle(RegistryKey rKey)
{
    return rKey.Handle.DangerousGetHandle;
}

, , , , . MSDN

DangerousGetHandle , , SetHandleAsInvalid, DangerousGetHandle , . . , . , , , , . , . . DangerousAddRef DangerousRelease DangerousGetHandle.

+4

All Articles