Questa è la prima volta in assoluto che userò SafeHandle
.Perché SafeHandle.DangerousGetHandle() "Pericoloso"?
Devo chiamare questo metodo P/Invoke che richiede un UIntPtr.
[DllImport("advapi32.dll", CharSet = CharSet.Auto)] public static extern int RegOpenKeyEx( UIntPtr hKey, string subKey, int ulOptions, int samDesired, out UIntPtr hkResult);
Questo UIntPtr sarà derivata dalla classe RegistryKey di .NET. Userò il metodo di cui sopra per convertire la classe RegistryKey a un IntPtr modo da poter utilizzare quanto sopra 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;
}
}
Domande:
- c'è un modo migliore per scrivere questo senza usare maniglie "non sicure"?
- Perché le maniglie non sicure sono pericolose?
Ho dimenticato di dire che lo scopo del mio codice è imitare il supporto del registro a 64 bit di NETFX4. Utilizziamo solo NETFX 3.5, quindi non è disponibile SafeRegistryHandle. – Ian
Basta renderlo SafeHandleZeroOrMinusOneIsInvalid, la classe base di SafeRegistryHandle. O semplicemente SafeHandle se si odia digitare il nome (chi no). –