IntPtr 結構

定義

平台專用的類型,用以代表指標或控點。A platform-specific type that is used to represent a pointer or a handle.

public value class IntPtr
public value class IntPtr : IComparable, IComparable<IntPtr>, IEquatable<IntPtr>, IFormattable, System::Runtime::Serialization::ISerializable
public value class IntPtr : IEquatable<IntPtr>, System::Runtime::Serialization::ISerializable
public value class IntPtr : System::Runtime::Serialization::ISerializable
public struct IntPtr
public struct IntPtr : IComparable, IComparable<IntPtr>, IEquatable<IntPtr>, IFormattable, System.Runtime.Serialization.ISerializable
public struct IntPtr : IEquatable<IntPtr>, System.Runtime.Serialization.ISerializable
[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
type nativeint = struct
type nativeint = struct
    interface IFormattable
    interface ISerializable
type nativeint = struct
    interface ISerializable
[<System.Serializable>]
type nativeint = struct
    interface ISerializable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type nativeint = struct
    interface ISerializable
Public Structure IntPtr
Public Structure IntPtr
Implements IComparable, IComparable(Of IntPtr), IEquatable(Of IntPtr), IFormattable, ISerializable
Public Structure IntPtr
Implements IEquatable(Of IntPtr), ISerializable
Public Structure IntPtr
Implements ISerializable
繼承
IntPtr
屬性
實作

範例

下列範例會使用 managed 指標來反轉陣列中的字元。The following example uses managed pointers to reverse the characters in an array. 初始化 String 物件並取得其長度之後,它會執行下列動作:After it initializes a String object and gets its length, it does the following:

  1. 呼叫 Marshal.StringToHGlobalAnsi 方法,將 Unicode 字串以 ANSI (一位元組) 字元的形式複製到非受控記憶體。Calls the Marshal.StringToHGlobalAnsi method to copy the Unicode string to unmanaged memory as an ANSI (one-byte) character. 方法 IntPtr 會傳回指向非受控字串開頭的物件。The method returns an IntPtr object that points to the beginning of the unmanaged string. Visual Basic 範例會直接使用此指標;在 c + + 和 c # 範例中,它會轉換為位元組的指標。The Visual Basic example uses this pointer directly; in the C++ and C# examples, it is cast to a pointer to a byte.

  2. 呼叫 Marshal.AllocHGlobal 方法,以配置與非受控字串佔用的位元組數目。Calls the Marshal.AllocHGlobal method to allocate the same number of bytes as the unmanaged string occupies. 方法 IntPtr 會傳回指向非受控記憶體區塊開頭的物件。The method returns an IntPtr object that points to the beginning of the unmanaged block of memory. Visual Basic 範例會直接使用此指標;在 c + + 和 c # 範例中,它會轉換為位元組的指標。The Visual Basic example uses this pointer directly; in the C++ and C# examples, it is cast to a pointer to a byte.

  3. Visual Basic 範例會定義名為 offset 的變數,該變數等於 ANSI 字串的長度。The Visual Basic example defines a variable named offset that is equal to the length of the ANSI string. 它是用來判斷在非受控記憶體中的位移,這是要將 ANSI 字串中的下一個字元複製到其中的位置。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.

    C # 和 c + + 範例 ToPointer 會呼叫方法,以取得字串的起始位址和未受管理的記憶體區塊的非受控指標,並將小於字串長度的一個指標加入至 ANSI 字串的起始位址。The C# 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.

  4. 使用迴圈,將字串中的每個字元複製到未受管理的記憶體區塊。Uses a loop to copy each character from the string to the unmanaged block of memory.

    Visual Basic 範例會呼叫 Marshal.ReadByte(IntPtr, Int32) 方法,以從 managed 指標的指定位移讀取位元組 (或一個位元組字元) 至 ANSI 字串。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. 然後,它會呼叫 Marshal.WriteByte(IntPtr, Int32, Byte) 方法,以將位元組寫入至由非受控記憶體區塊的起始位址所定義的記憶體位址,再加上 offsetIt 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. 然後,它會遞減 offsetIt then decrements offset.

    C # 和 c + + 範例會執行複製作業,然後將指標遞減至非受控 ANSI 字串中下一個位置的位址,並將指標遞增至非受控區塊中的下一個位址。The C# 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.

  5. 所有範例都會呼叫, Marshal.PtrToStringAnsi 以將包含複製之 ANSI 字串的非受控記憶體區塊轉換為 Managed Unicode String 物件。All examples call the Marshal.PtrToStringAnsi to convert the unmanaged memory block containing the copied ANSI string to a managed Unicode String object.

  6. 顯示原始和反轉字串之後,所有範例都會呼叫方法來釋出配置給 FreeHGlobal 非受控 ANSI 字串和非受控記憶體區塊的記憶體。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
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

備註

IntPtr 類型的設計是,其大小為平臺特定的整數。The IntPtr type is designed to be an integer whose size is platform-specific. 也就是說,此類型的實例必須是 32-32 位硬體和作業系統上的位,以及64位硬體和作業系統上的64位。That is, an instance of this type is expected to be 32-bits on 32-bit hardware and operating systems, and 64-bits on 64-bit hardware and operating systems.

IntPtr 類型可供支援指標的語言使用,以及在執行和不支援指標的語言之間參考資料的常見方法。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 物件也可以用來保存控制碼。IntPtr objects can also be used to hold handles. 例如,在 IntPtr 類別中廣泛使用的實例 System.IO.FileStream 來保存檔案控制代碼。For example, instances of IntPtr are used extensively in the System.IO.FileStream class to hold file handles.

IntPtr類型符合 CLS 規範,而 UIntPtr 類型則否。The IntPtr type is CLS-compliant, while the UIntPtr type is not. IntPtrCommon language runtime 中只會使用類型。Only the IntPtr type is used in the common language runtime. UIntPtr 類型主要是為了維持與型別之間的架構對稱而提供 IntPtrThe UIntPtr type is provided mostly to maintain architectural symmetry with the IntPtr type.

這個型別會 ISerializable 在 .net 5.0 和更新版本中,實作為 IFormattable 介面。This type implements the ISerializable, and, in .NET 5.0 and later, the IFormattable interfaces.

建構函式

IntPtr(Int32)

使用指定的 32 位元指標或控點,初始化 IntPtr 的新執行個體。Initializes a new instance of IntPtr using the specified 32-bit pointer or handle.

IntPtr(Int64)

使用指定的 64 位元指標,初始化 IntPtr 的新執行個體。Initializes a new instance of IntPtr using the specified 64-bit pointer.

IntPtr(Void*)

對未指定的類型使用指定的指標,初始化 IntPtr 的新執行個體。Initializes a new instance of IntPtr using the specified pointer to an unspecified type.

欄位

Zero

表示已經初始化為零的指標或控點之唯讀欄位。A read-only field that represents a pointer or handle that has been initialized to zero.

屬性

MaxValue

代表 IntPtr 最大的可能值。Represents the largest possible value of IntPtr.

MinValue

代表 IntPtr 最小的可能值。Represents the smallest possible value of IntPtr.

Size

取得這個執行個體的大小。Gets the size of this instance.

方法

Add(IntPtr, Int32)

將指標的值加上位移。Adds an offset to the value of a pointer.

CompareTo(IntPtr)

將目前的執行個體與相同類型的另一個物件相比較,並傳回整數,這個整數表示目前的執行個體在排序次序中,位於另一個物件之前、之後或相同位置。Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.

CompareTo(Object)

將目前的執行個體與相同類型的另一個物件相比較,並傳回整數,這個整數表示目前的執行個體在排序次序中,位於另一個物件之前、之後或相同位置。Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.

Equals(IntPtr)

指出目前的物件是否等於另一個相同類型的物件。Indicates whether the current object is equal to another object of the same type.

Equals(Object)

傳回值,該值表示這個執行個體是否和指定的物件相等。Returns a value indicating whether this instance is equal to a specified object.

GetHashCode()

傳回這個執行個體的雜湊碼。Returns the hash code for this instance.

Parse(String)

將數字的字串表示轉換成其對等帶正負號的原生整數。Converts the string representation of a number to its signed native integer equivalent.

Parse(String, IFormatProvider)

將指定特定文化特性 (Culture) 格式之數字的字串表示法轉換成其對等帶正負號的原生整數。Converts the string representation of a number in a specified culture-specific format to its signed native integer equivalent.

Parse(String, NumberStyles)

將指定樣式之數字的字串表示法轉換成其對等帶正負號的原生整數。Converts the string representation of a number in a specified style to its signed native integer equivalent.

Parse(String, NumberStyles, IFormatProvider)

將指定樣式與文化特性 (Culture) 特定格式之數字的字串表示法轉換成其對等帶正負號的原生整數。Converts the string representation of a number in a specified style and culture-specific format to its signed native integer equivalent.

Subtract(IntPtr, Int32)

將指標值減去移位。Subtracts an offset from the value of a pointer.

ToInt32()

將這個執行個體的值轉換為 32 位元帶正負號的整數。Converts the value of this instance to a 32-bit signed integer.

ToInt64()

將這個執行個體的值轉換為 64 位元帶正負號的整數。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()

將目前 IntPtr 物件的數值,轉換為其相等的字串表示。Converts the numeric value of the current IntPtr object to its equivalent string representation.

ToString(IFormatProvider)

使用指定的格式和特定文化特性格式資訊,將這個執行個體的數值轉換成它的相等字串表示。Converts the numeric value of this instance to its equivalent string representation using the specified format and culture-specific format information.

ToString(String)

將目前 IntPtr 物件的數值,轉換為其相等的字串表示。Converts the numeric value of the current IntPtr object to its equivalent string representation.

ToString(String, IFormatProvider)

使用指定的格式,格式化目前執行個體的值。Formats the value of the current instance using the specified format.

TryParse(String, IntPtr)

將數字的字串表示轉換成其對等帶正負號的原生整數。Converts the string representation of a number to its signed native integer equivalent. 傳回指示轉換是否成功的值。A return value indicates whether the conversion succeeded.

TryParse(String, NumberStyles, IFormatProvider, IntPtr)

將指定樣式與文化特性 (Culture) 特定格式之數字的字串表示法轉換成其對等帶正負號的原生整數。Converts the string representation of a number in a specified style and culture-specific format to its signed native integer equivalent. 傳回指示轉換是否成功的值。A return value indicates whether the conversion succeeded.

運算子

Addition(IntPtr, Int32)

將指標的值加上位移。Adds an offset to the value of a pointer.

Equality(IntPtr, IntPtr)

判斷 IntPtr 的兩個指定執行個體是否相等。Determines whether two specified instances of IntPtr are equal.

Explicit(Int32 to IntPtr)

將 32 位元帶正負號整數的值轉換為 IntPtrConverts the value of a 32-bit signed integer to an IntPtr.

Explicit(Int64 to IntPtr)

將 64 位元帶正負號整數的值轉換為 IntPtrConverts the value of a 64-bit signed integer to an IntPtr.

Explicit(IntPtr to Int32)

將指定的 IntPtr 值轉換為 32 位元帶正負號的整數。Converts the value of the specified IntPtr to a 32-bit signed integer.

Explicit(IntPtr to Int64)

將指定的 IntPtr 值轉換為 64 位元帶正負號的整數。Converts the value of the specified IntPtr to a 64-bit signed integer.

Explicit(IntPtr to Void*)

將指定的 IntPtr 值轉換為未指定的類型指標。Converts the value of the specified IntPtr to a pointer to an unspecified type.

此應用程式開發介面不符合 CLS 標準。This API is not CLS-compliant.

Explicit(Void* to IntPtr)

將指定的指標轉換為 IntPtr 的未指定類型。Converts the specified pointer to an unspecified type to an IntPtr.

此應用程式開發介面不符合 CLS 標準。This API is not CLS-compliant.

Inequality(IntPtr, IntPtr)

判斷 IntPtr 的兩個指定執行個體是否不相等。Determines whether two specified instances of IntPtr are not equal.

Subtraction(IntPtr, Int32)

將指標值減去移位。Subtracts an offset from the value of a pointer.

明確介面實作

IEquatable<IntPtr>.Equals(IntPtr)

傳回值,該值表示這個執行個體是否等於其他帶正負號的整數指標。Returns a value that indicates whether this instance is equal to another signed integer pointer.

ISerializable.GetObjectData(SerializationInfo, StreamingContext)

使用序列化目前 SerializationInfo 物件所需的資料,填入 IntPtr 物件。Populates a SerializationInfo object with the data needed to serialize the current IntPtr object.

適用於

執行緒安全性

此型別具備執行緒安全。This type is thread safe.

另請參閱