初めてSafeHandle
を使用します。SafeHandle.DangerousGetHandle()はなぜ危険なのですか?
UIntPtrが必要なこのP/Invokeメソッドを呼び出す必要があります。
[DllImport("advapi32.dll", CharSet = CharSet.Auto)] public static extern int RegOpenKeyEx( UIntPtr hKey, string subKey, int ulOptions, int samDesired, out UIntPtr hkResult);
このUIntPtrは、.NETののRegistryKeyクラスから派生されます。使用せずにこれを書くためのより良い方法はあり
- :
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; } }
質問:私は、私は上記のP /呼び出しを使用することができるのIntPtrへのRegistryKeyクラスを変換するために、上記の方法を使用することになります「安全でない」ハンドル?
- なぜ安全でないハンドルは危険ですか?
私のコードの目的は、NETFX4の64ビットレジストリサポートを模倣することであることを忘れてしまいました。私たちはNETFX 3.5しか使用していないので、SafeRegistryHandleは利用できません。 – Ian
SafeRandryHandleの基本クラスSafeHandleZeroOrMinusOneIsInvalidにします。あなたが名前を入力することを嫌うならば、SafeHandleを単なる普通のもの(誰もいない)。 –