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 클래스에서 파생됩니다. 나는 그래서 위의 P를 사용할 수있는 IntPtr입니다에 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; } }
질문 :
- 사용하지 않고 쓰기에 더 좋은 방법이 있나요 "안전하지 않은"핸들?
- 왜 안전하지 않은 핸들이 위험합니까?
내 코드의 목적은 NETFX4의 64 비트 레지스트리 지원을 모방하는 것임을 언급하는 것을 잊어 버렸습니다. 우리는 NETFX 3.5 만 사용하므로 SafeRegistryHandle을 사용할 수 없습니다. – Ian
SafeRandistryHandle의 기본 클래스 인 SafeHandleZeroOrMinusOneIsInvalid로 설정하면됩니다. 또는 이름을 입력하는 것을 싫어하면 그냥 평범한 SafeHandle (누가하지 않는가)입니다. –