IntPtr Struct
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Represents a signed integer where the bit-width is the same as a pointer.
public value class IntPtr
public value class IntPtr : System::Runtime::Serialization::ISerializable
public value class IntPtr : IEquatable<IntPtr>, System::Runtime::Serialization::ISerializable
public struct IntPtr
[System.Serializable]
public struct IntPtr : System.Runtime.Serialization.ISerializable
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public struct IntPtr : System.Runtime.Serialization.ISerializable
public struct IntPtr : System.Runtime.Serialization.ISerializable
public readonly struct IntPtr : IEquatable<IntPtr>, System.Runtime.Serialization.ISerializable
type nativeint = struct
[<System.Serializable>]
type nativeint = struct
interface ISerializable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type nativeint = struct
interface ISerializable
type nativeint = struct
interface ISerializable
Public Structure IntPtr
Public Structure IntPtr
Implements ISerializable
Public Structure IntPtr
Implements IEquatable(Of IntPtr), ISerializable
- Inheritance
- Attributes
- Implements
Examples
The following example uses managed pointers to reverse the characters in an array. After it initializes a String object and gets its length, it does the following:
Calls the Marshal.StringToHGlobalAnsi method to copy the Unicode string to unmanaged memory as an ANSI (one-byte) character. The method returns an IntPtr object that points to the beginning of the unmanaged string. The Visual Basic example uses this pointer directly; in the C++, F# and C# examples, it is cast to a pointer to a byte.
Calls the Marshal.AllocHGlobal method to allocate the same number of bytes as the unmanaged string occupies. The method returns an IntPtr object that points to the beginning of the unmanaged block of memory. The Visual Basic example uses this pointer directly; in the C++, F# and C# examples, it is cast to a pointer to a byte.
The Visual Basic example defines a variable named
offsetthat is equal to the length of the ANSI string. It is used to determine the offset into unmanaged memory to which the next character in the ANSI string is copied. Because its starting value is the length of the string, the copy operation will copy a character from the start of the string to the end of the memory block.The C#, F# and C++ examples call the ToPointer method to get an unmanaged pointer to the starting address of the string and the unmanaged block of memory, and they add one less than the length of the string to the starting address of the ANSI string. Because the unmanaged string pointer now points to the end of the string, the copy operation will copy a character from the end of the string to the start of the memory block.
Uses a loop to copy each character from the string to the unmanaged block of memory.
The Visual Basic example calls the Marshal.ReadByte(IntPtr, Int32) method to read the byte (or one-byte character) at a specified offset from the managed pointer to the ANSI string. The offset is incremented with each iteration of the loop. It then calls the Marshal.WriteByte(IntPtr, Int32, Byte) method to write the byte to the memory address defined by the starting address of the unmanaged block of memory plus
offset. It then decrementsoffset.The C#, F# and C++ examples perform the copy operation, then decrement the pointer to the address of the next location in the unmanaged ANSI string and increment the pointer to the next address in the unmanaged block.
All examples call the Marshal.PtrToStringAnsi to convert the unmanaged memory block containing the copied ANSI string to a managed Unicode String object.
After displaying the original and reversed strings, all examples call the FreeHGlobal method to free the memory allocated for the unmanaged ANSI string and the unmanaged block of memory.
using namespace System;
using namespace System::Runtime::InteropServices;
class NotTooSafeStringReverse
{
public:
static void Main()
{
String^ stringA = "I seem to be turned around!";
int copylen = stringA->Length;
// Allocate HGlobal memory for source and destination strings
IntPtr sptr = Marshal::StringToHGlobalAnsi(stringA);
IntPtr dptr = Marshal::AllocHGlobal(copylen + 1);
char *src = (char *)sptr.ToPointer();
char *dst = (char *)dptr.ToPointer();
if (copylen > 0)
{
// set the source pointer to the end of the string
// to do a reverse copy.
src += copylen - 1;
while (copylen-- > 0)
{
*dst++ = *src--;
}
*dst = 0;
}
String^ stringB = Marshal::PtrToStringAnsi(dptr);
Console::WriteLine("Original:\n{0}\n", stringA);
Console::WriteLine("Reversed:\n{0}", stringB);
// Free HGlobal memory
Marshal::FreeHGlobal(dptr);
Marshal::FreeHGlobal(sptr);
}
};
int main()
{
NotTooSafeStringReverse::Main();
}
// The progam has the following output:
//
// Original:
// I seem to be turned around!
//
// Reversed:
// !dnuora denrut eb ot mees I
using System;
using System.Runtime.InteropServices;
class NotTooSafeStringReverse
{
static public void Main()
{
string stringA = "I seem to be turned around!";
int copylen = stringA.Length;
// Allocate HGlobal memory for source and destination strings
IntPtr sptr = Marshal.StringToHGlobalAnsi(stringA);
IntPtr dptr = Marshal.AllocHGlobal(copylen + 1);
// The unsafe section where byte pointers are used.
unsafe
{
byte *src = (byte *)sptr.ToPointer();
byte *dst = (byte *)dptr.ToPointer();
if (copylen > 0)
{
// set the source pointer to the end of the string
// to do a reverse copy.
src += copylen - 1;
while (copylen-- > 0)
{
*dst++ = *src--;
}
*dst = 0;
}
}
string stringB = Marshal.PtrToStringAnsi(dptr);
Console.WriteLine("Original:\n{0}\n", stringA);
Console.WriteLine("Reversed:\n{0}", stringB);
// Free HGlobal memory
Marshal.FreeHGlobal(dptr);
Marshal.FreeHGlobal(sptr);
}
}
// The progam has the following output:
//
// Original:
// I seem to be turned around!
//
// Reversed:
// !dnuora denrut eb ot mees I
#nowarn "9"
open System.Runtime.InteropServices
open FSharp.NativeInterop
[<EntryPoint>]
let main _ =
let stringA = "I seem to be turned around!"
let mutable copylen = stringA.Length
// Allocate HGlobal memory for source and destination strings
let sptr = Marshal.StringToHGlobalAnsi stringA
let dptr = Marshal.AllocHGlobal(copylen + 1)
let mutable src: byte nativeptr = sptr.ToPointer() |> NativePtr.ofVoidPtr
let mutable dst: byte nativeptr = dptr.ToPointer() |> NativePtr.ofVoidPtr
if copylen > 0 then
// set the source pointer to the end of the string
// to do a reverse copy.
src <-
NativePtr.toNativeInt src + nativeint (copylen - 1)
|> NativePtr.ofNativeInt
while copylen > 0 do
copylen <- copylen - 1
NativePtr.read src |> NativePtr.write dst
dst <- NativePtr.toNativeInt dst + 1n |> NativePtr.ofNativeInt
src <- NativePtr.toNativeInt src - 1n |> NativePtr.ofNativeInt
NativePtr.write dst 0uy
let stringB = Marshal.PtrToStringAnsi dptr
printfn $"Original:\n{stringA}\n"
printfn $"Reversed:\n{stringB}"
// Free HGlobal memory
Marshal.FreeHGlobal dptr
Marshal.FreeHGlobal sptr
0
// The progam has the following output:
//
// Original:
// I seem to be turned around!
//
// Reversed:
// !dnuora denrut eb ot mees I
Imports System.Runtime.InteropServices
Public Module Example
Public Sub Main()
Dim stringA As String = "I seem to be turned around!"
Dim copylen As Integer = stringA.Length
' Allocate HGlobal memory for source and destination strings
Dim sptr As IntPtr = Marshal.StringToHGlobalAnsi(stringA)
Dim dptr As IntPtr = Marshal.AllocHGlobal(copylen)
Dim offset As Integer = copylen - 1
For ctr As Integer = 0 To copylen - 1
Dim b As Byte = Marshal.ReadByte(sptr, ctr)
Marshal.WriteByte(dptr, offset, b)
offset -= 1
Next
Dim stringB As String = Marshal.PtrToStringAnsi(dptr)
Console.WriteLine("Original:{1}{0}{1}", stringA, vbCrLf)
Console.WriteLine("Reversed:{1}{0}{1}", stringB, vbCrLf)
' Free HGlobal memory
Marshal.FreeHGlobal(dptr)
Marshal.FreeHGlobal(sptr)
End Sub
End Module
' The example displays the following output:
' Original:
' I seem to be turned around!
'
' Reversed:
' !dnuora denrut eb ot mees I
Remarks
The IntPtr type is designed to be an integer whose size is the same as a pointer. That is, an instance of this type is expected to be 32 bits in a 32-bit process and 64 bits in a 64-bit process.
The IntPtr type can be used by languages that support pointers and as a common means of referring to data between languages that do and do not support pointers.
IntPtr objects can also be used to hold handles. For example, instances of IntPtr are used extensively in the System.IO.FileStream class to hold file handles.
Note
Using IntPtr as a pointer or a handle is error prone and unsafe. It is simply an integer type that can be used as an interchange format for pointers and handles due to being the same size. Outside of specific interchange requirements, such as for passing data to a language that doesn't support pointers, a correctly typed pointer should be used to represent pointers and SafeHandle should be used to represent handles.
This type implements the ISerializable. In .NET 5 and later versions, this type also implements the IFormattable interfaces. In .NET 7 and later versions, this type also implements the IBinaryInteger<TSelf>, IMinMaxValue<TSelf>, and ISignedNumber<TSelf> interfaces.
In C# starting from version 9.0, you can use the built-in nint type to define native-sized integers. This type is represented by the IntPtr type internally and provides operations and conversions that are appropriate for integer types. For more information, see nint and nuint types.
In C# starting from version 11 and when targeting the .NET 7 or later runtime, nint is an alias for IntPtr in the same way that int is an alias for Int32.
Constructors
| Name | Description |
|---|---|
| IntPtr(Int32) |
Initializes a new instance of IntPtr using the specified 32-bit signed integer. |
| IntPtr(Int64) |
Initializes a new instance of IntPtr using the specified 64-bit signed integer. |
| IntPtr(Void*) |
Initializes a new instance of IntPtr using the specified pointer to an unspecified type. |
Fields
| Name | Description |
|---|---|
| Zero |
A read-only field that represents a signed integer that has been initialized to zero. |
Properties
| Name | Description |
|---|---|
| Size |
Gets the size of this instance. |
Methods
| Name | Description |
|---|---|
| Add(IntPtr, Int32) |
Adds an offset to a signed integer. |
| Equals(Object) |
Returns a value indicating whether this instance is equal to a specified object. |
| GetHashCode() |
Returns the hash code for this instance. |
| Subtract(IntPtr, Int32) |
Subtracts an offset from a signed integer. |
| ToInt32() |
Converts the value of this instance to a 32-bit signed integer. |
| ToInt64() |
Converts the value of this instance to a 64-bit signed integer. |
| ToPointer() |
Converts the value of this instance to a pointer to an unspecified type. |
| ToString() |
Converts the numeric value of the current IntPtr object to its equivalent string representation. |
| ToString(String) |
Converts the numeric value of the current IntPtr object to its equivalent string representation. |
Operators
| Name | Description |
|---|---|
| Addition(IntPtr, Int32) |
Adds an offset to a signed integer. |
| Equality(IntPtr, IntPtr) |
Determines whether two specified instances of IntPtr are equal. |
| Explicit(Int32 to IntPtr) |
Converts the value of a 32-bit signed integer to an IntPtr. |
| Explicit(Int64 to IntPtr) |
Converts the value of a 64-bit signed integer to an IntPtr. |
| Explicit(IntPtr to Int32) |
Converts the value of the specified IntPtr to a 32-bit signed integer. |
| Explicit(IntPtr to Int64) |
Converts the value of the specified IntPtr to a 64-bit signed integer. |
| Explicit(IntPtr to Void*) |
Converts the value of the specified IntPtr to a pointer to an unspecified type. This API is not CLS-compliant. |
| Explicit(Void* to IntPtr) |
Converts the specified pointer to an unspecified type to an IntPtr. This API is not CLS-compliant. |
| Inequality(IntPtr, IntPtr) |
Determines whether two specified instances of IntPtr are not equal. |
| Subtraction(IntPtr, Int32) |
Subtracts an offset from a signed integer. |
Explicit Interface Implementations
| Name | Description |
|---|---|
| IEquatable<IntPtr>.Equals(IntPtr) |
Returns a value that indicates whether this instance is equal to another signed integer. |
| ISerializable.GetObjectData(SerializationInfo, StreamingContext) |
Populates a SerializationInfo object with the data needed to serialize the current IntPtr object. |
Applies to
Thread Safety
This type is thread safe.