- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
这是我第一次使用 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;
}
}
问题:
最佳答案
RegistryKey 有一个 handle 属性。所以你可以使用
private static IntPtr GetRegistryKeyHandle(RegistryKey rKey)
{
return rKey.Handle.DangerousGetHandle();
}
这有潜在的危险,因为您获得的指针在您使用时可能不再有效。引自 MSDN
Using the DangerousGetHandle method can pose security risks because, if the handle has been marked as invalid with SetHandleAsInvalid, DangerousGetHandle still returns the original, potentially stale handle value. The returned handle can also be recycled at any point. At best, this means the handle might suddenly stop working. At worst, if the handle or the resource that the handle represents is exposed to untrusted code, this can lead to a recycling security attack on the reused or returned handle. For example, an untrusted caller can query data on the handle just returned and receive information for an entirely unrelated resource. See the DangerousAddRef and the DangerousRelease methods for more information about using the DangerousGetHandle methodsafely.
关于c# - 为什么 SafeHandle.DangerousGetHandle() "Dangerous"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8396923/
这是我第一次使用 SafeHandle。 我需要调用这个需要 UIntPtr 的 P/Invoke 方法。 [DllImport("advapi32.dll", CharSet = CharS
我是一名优秀的程序员,十分优秀!