UIntPtr Struct
Represents an unsigned integer pointer or handle. This type is a common synonym for size_t
in C++ and is used in .NET to represent memory addresses and handles. It is platform-dependent, meaning its size (32-bit or 64-bit) varies based on the underlying operating system architecture.
Summary
-
Zeropublic static readonly System.UIntPtr Zero;
Represents an uninitialized UIntPtr, which is equivalent to zero.
-
op_Explicitpublic static explicit operator System.UIntPtr(ulong value); public static explicit operator ulong(System.UIntPtr value);
Provides explicit conversion between
ulong
andUIntPtr
. -
Equalspublic override bool Equals(object obj); public bool Equals(System.UIntPtr other);
Determines whether the specified object is equal to the current object.
-
GetHashCodepublic override int GetHashCode();
Serves as the default hash function.
-
ToStringpublic override string ToString();
Returns a string representation of the value.
Remarks
The UIntPtr
type is a value type that is used to represent a pointer or handle. It is a 32-bit unsigned integer on 32-bit systems and a 64-bit unsigned integer on 64-bit systems. This type is commonly used in interoperation scenarios with native code or when dealing with memory addresses directly.
You can use UIntPtr
to store memory addresses, such as the address of an array element or the starting address of a block of memory. It can also be used to represent handles to system resources, like file handles or process handles, although the IntPtr
type is often preferred for this purpose.
Example
using System;
public class UIntPtrExample
{
public static void Main(string[] args)
{
// Create a UIntPtr from a ulong
ulong addressValue = 0x1234567890ABCDEF;
System.UIntPtr ptr = new System.UIntPtr(addressValue);
Console.WriteLine($"UIntPtr value: {ptr}");
Console.WriteLine($"UIntPtr as ulong: {(ulong)ptr}");
// Check if it's the zero pointer
if (ptr == System.UIntPtr.Zero)
{
Console.WriteLine("This is the zero pointer.");
}
else
{
Console.WriteLine("This is not the zero pointer.");
}
// Example with potential memory allocation (simplified)
// In real scenarios, this would involve unsafe code or P/Invoke
byte[] data = new byte[100];
// Assume 'data' is allocated in memory and we get its address
System.UIntPtr dataAddress = (System.UIntPtr)(ulong)System.Runtime.InteropServices.GCHandle.Alloc(data).AddrOfPinnedObject();
Console.WriteLine($"Address of byte array: {dataAddress}");
}
}