IntPtr IntPtr IntPtr IntPtr Struct

定义

用于表示指针或句柄的平台特定类型。A platform-specific type that is used to represent a pointer or a handle.

public value class IntPtr : System::Runtime::Serialization::ISerializable
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public struct IntPtr : System.Runtime.Serialization.ISerializable
type nativeint = struct
    interface ISerializable
Public Structure IntPtr
Implements ISerializable
继承
属性
实现

示例

下面的示例使用托管指针来反转数组中的字符。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 charter 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)方法,以从托管指针到 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)方法,将字节写入到由非托管offset内存块的起始地址定义的内存地址。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. 然后,它offset会递减。It 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 字符串的非托管内存块转换为托管String的 Unicode 对象。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. 例如,在System.IO.FileStream类中IntPtr广泛使用的实例,以保存文件句柄。For example, instances of IntPtr are used extensively in the System.IO.FileStream class to hold file handles.

类型符合 CLS, UIntPtr而类型则为。 IntPtrThe IntPtr type is CLS-compliant, while the UIntPtr type is not. 仅在公共语言运行时中使用类型。IntPtrOnly the IntPtr type is used in the common language runtime. 提供UIntPtr此类型主要是为了维护IntPtr类型的体系结构对称。The UIntPtr type is provided mostly to maintain architectural symmetry with the IntPtr type.

此类型实现 ISerializable 接口。This type implements the ISerializable interface.

构造函数

IntPtr(Int32) IntPtr(Int32) IntPtr(Int32) IntPtr(Int32)

使用指定的 32 位指针或句柄初始化 IntPtr 的新实例。Initializes a new instance of IntPtr using the specified 32-bit pointer or handle.

IntPtr(Int64) IntPtr(Int64) IntPtr(Int64) IntPtr(Int64)

使用指定的 64 位指针初始化 IntPtr 的新实例。Initializes a new instance of IntPtr using the specified 64-bit pointer.

IntPtr(Void*) IntPtr(Void*) IntPtr(Void*) IntPtr(Void*)

使用指定的指向未指定类型的指针初始化 IntPtr 的新实例。Initializes a new instance of IntPtr using the specified pointer to an unspecified type.

字段

Zero Zero Zero Zero

表示已初始化为零的指针或句柄的只读字段。A read-only field that represents a pointer or handle that has been initialized to zero.

属性

Size Size Size Size

获取此实例的大小。Gets the size of this instance.

方法

Add(IntPtr, Int32) Add(IntPtr, Int32) Add(IntPtr, Int32) Add(IntPtr, Int32)

为指针值添加偏移量。Adds an offset to the value of a pointer.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

返回一个值,该值指示此实例是否等于指定的对象。Returns a value indicating whether this instance is equal to a specified object.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

返回此实例的哈希代码。Returns the hash code for this instance.

Subtract(IntPtr, Int32) Subtract(IntPtr, Int32) Subtract(IntPtr, Int32) Subtract(IntPtr, Int32)

从指针值中减去偏移量。Subtracts an offset from the value of a pointer.

ToInt32() ToInt32() ToInt32() ToInt32()

将此实例的值转换为 32 位有符号整数。Converts the value of this instance to a 32-bit signed integer.

ToInt64() ToInt64() ToInt64() ToInt64()

将此实例的值转换为 64 位有符号整数。Converts the value of this instance to a 64-bit signed integer.

ToPointer() ToPointer() ToPointer() ToPointer()

将此实例的值转换为指向未指定类型的指针。Converts the value of this instance to a pointer to an unspecified type.

ToString(String) ToString(String) ToString(String) ToString(String)

将当前 IntPtr 对象的数值转换为其等效字符串表示形式。Converts the numeric value of the current IntPtr object to its equivalent string representation.

ToString() ToString() ToString() ToString()

将当前 IntPtr 对象的数值转换为其等效字符串表示形式。Converts the numeric value of the current IntPtr object to its equivalent string representation.

操作员

Addition(IntPtr, Int32) Addition(IntPtr, Int32) Addition(IntPtr, Int32) Addition(IntPtr, Int32)

为指针值添加偏移量。Adds an offset to the value of a pointer.

Equality(IntPtr, IntPtr) Equality(IntPtr, IntPtr) Equality(IntPtr, IntPtr) Equality(IntPtr, IntPtr)

确定 IntPtr 的两个指定的实例是否相等。Determines whether two specified instances of IntPtr are equal.

Explicit(Void* to IntPtr) Explicit(Void* to IntPtr) Explicit(Void* to IntPtr) Explicit(Void* to IntPtr)

将指向未指定类型的指定指针转换为 IntPtrConverts the specified pointer to an unspecified type to an IntPtr.

此 API 不兼容 CLS。This API is not CLS-compliant.

Explicit(IntPtr to Int64) Explicit(IntPtr to Int64) Explicit(IntPtr to Int64) Explicit(IntPtr to Int64)

将指定的 IntPtr 的值转换为 64 位有符号整数。Converts the value of the specified IntPtr to a 64-bit signed integer.

Explicit(IntPtr to Void*) Explicit(IntPtr to Void*) Explicit(IntPtr to Void*) Explicit(IntPtr to Void*)

将指定的 IntPtr 的值转换为指向未指定类型的指针。Converts the value of the specified IntPtr to a pointer to an unspecified type.

此 API 不兼容 CLS。This API is not CLS-compliant.

Explicit(Int64 to IntPtr) Explicit(Int64 to IntPtr) Explicit(Int64 to IntPtr) Explicit(Int64 to IntPtr)

将 64 位有符号整数值转换为 IntPtrConverts the value of a 64-bit signed integer to an IntPtr.

Explicit(Int32 to IntPtr) Explicit(Int32 to IntPtr) Explicit(Int32 to IntPtr) Explicit(Int32 to IntPtr)

将 32 位有符号整数的值转换为 IntPtrConverts the value of a 32-bit signed integer to an IntPtr.

Explicit(IntPtr to Int32) Explicit(IntPtr to Int32) Explicit(IntPtr to Int32) Explicit(IntPtr to Int32)

将指定的 IntPtr 的值转换为 32 位有符号整数。Converts the value of the specified IntPtr to a 32-bit signed integer.

Inequality(IntPtr, IntPtr) Inequality(IntPtr, IntPtr) Inequality(IntPtr, IntPtr) Inequality(IntPtr, IntPtr)

确定 IntPtr 的两个指定的实例是否不等。Determines whether two specified instances of IntPtr are not equal.

Subtraction(IntPtr, Int32) Subtraction(IntPtr, Int32) Subtraction(IntPtr, Int32) Subtraction(IntPtr, Int32)

从指针值中减去偏移量。Subtracts an offset from the value of a pointer.

显式界面实现

IEquatable<IntPtr>.Equals(IntPtr) IEquatable<IntPtr>.Equals(IntPtr) IEquatable<IntPtr>.Equals(IntPtr) IEquatable<IntPtr>.Equals(IntPtr)
ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) 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.

另请参阅