を使用するのはこれが初めてSafeHandle
です。
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 クラスから派生します。上記のメソッドを使用して RegistryKey クラスを IntPtr に変換し、上記の 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;
}
}
質問:
- 「安全でない」ハンドルを使用せずにこれを記述するより良い方法はありますか?
- アンセーフ ハンドルが危険なのはなぜですか?