I tried casting it like so:
UIntPtr x = (UIntPtr)intPtr;
... but the Compiler is not very happy with it and returned a compile error.
I need to do the conversion because the P/Invoke signature for RegOpenKeyEx requires a UIntPtr:
[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
public static extern int RegOpenKeyEx(
UIntPtr hKey,
string subKey,
int ulOptions,
int samDesired,
out UIntPtr hkResult);
In order to get a handle, I am using SafeHandle.DangerousHandle() which returns an IntPtr:
/// <summary>
/// Get a pointer to a registry key.
/// </summary>
/// <param name="registryKey">Registry key to obtain the pointer of.</param>
/// <returns>Pointer to the given registry key.</returns>
IntPtr _getRegistryKeyHandle(RegistryKey registryKey)
{
//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
SafeHandle handle = (SafeHandle)fieldInfo.GetValue(registryKey);
//Get the unsafe handle
IntPtr dangerousHandle = handle.DangerousGetHandle();
return dangerousHandle;
}
After taking a look at msdn i noticed that both, UIntPtr
and IntPtr
, have the void*
pointer conversion.
IntPtr a = ....;
UIntPtr b = (UIntPtr)a.ToPointer();
At this point you need unsafe code. The only way to avoid this is using the unchecked
keyword and convert by using non-pointer types ( used here too ).
The reason why there is no conversion between the two pointers might be that UIntPtr
like IntPtr
does not have a fixed size because they are platform specific( see ).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With