Esta es la primera vez que usaré SafeHandle
.¿Por qué SafeHandle.DangerousGetHandle() es "peligroso"?
Necesito llamar a este método P/Invoke que necesita un UIntPtr.
[DllImport("advapi32.dll", CharSet = CharSet.Auto)] public static extern int RegOpenKeyEx( UIntPtr hKey, string subKey, int ulOptions, int samDesired, out UIntPtr hkResult);
Este UIntPtr se derivará de clase RegistryKey de .NET. Me va a utilizar el método anterior para convertir la clase RegistryKey a un IntPtr para que pueda utilizar el P anterior/Invocar:
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;
}
}
Preguntas:
- ¿Hay una mejor manera de escribir esto sin usar ¿Mangos "inseguros"?
- ¿Por qué las asas inseguras son peligrosas?
Olvidé mencionar que el objetivo de mi código es imitar el soporte de registro de 64 bits de NETFX4. Solo estamos utilizando NETFX 3.5 por lo que no hay SafeRegistryHandle disponible. – Ian
Simplemente hágalo SafeHandleZeroOrMinusOneIsInvalid, la clase base de SafeRegistryHandle. O simplemente SafeHandle si odias escribir el nombre (quién no). –