IntPtr Struct

Definizione

Rappresenta un intero con segno in cui la larghezza del bit è uguale a un puntatore.

public value class IntPtr
public value class IntPtr : IComparable, IComparable<IntPtr>, IEquatable<IntPtr>, IFormattable, System::Runtime::Serialization::ISerializable
public value class IntPtr : IComparable, IComparable<IntPtr>, IEquatable<IntPtr>, ISpanFormattable, System::Runtime::Serialization::ISerializable
public value class IntPtr : IComparable<IntPtr>, IEquatable<IntPtr>, IParsable<IntPtr>, ISpanParsable<IntPtr>, System::Numerics::IAdditionOperators<IntPtr, IntPtr, IntPtr>, System::Numerics::IAdditiveIdentity<IntPtr, IntPtr>, System::Numerics::IBinaryInteger<IntPtr>, System::Numerics::IBinaryNumber<IntPtr>, System::Numerics::IBitwiseOperators<IntPtr, IntPtr, IntPtr>, System::Numerics::IComparisonOperators<IntPtr, IntPtr, bool>, System::Numerics::IDecrementOperators<IntPtr>, System::Numerics::IDivisionOperators<IntPtr, IntPtr, IntPtr>, System::Numerics::IEqualityOperators<IntPtr, IntPtr, bool>, System::Numerics::IIncrementOperators<IntPtr>, System::Numerics::IMinMaxValue<IntPtr>, System::Numerics::IModulusOperators<IntPtr, IntPtr, IntPtr>, System::Numerics::IMultiplicativeIdentity<IntPtr, IntPtr>, System::Numerics::IMultiplyOperators<IntPtr, IntPtr, IntPtr>, System::Numerics::INumber<IntPtr>, System::Numerics::INumberBase<IntPtr>, System::Numerics::IShiftOperators<IntPtr, int, IntPtr>, System::Numerics::ISignedNumber<IntPtr>, System::Numerics::ISubtractionOperators<IntPtr, IntPtr, IntPtr>, System::Numerics::IUnaryNegationOperators<IntPtr, IntPtr>, System::Numerics::IUnaryPlusOperators<IntPtr, IntPtr>, System::Runtime::Serialization::ISerializable
public value class IntPtr : IComparable<IntPtr>, IEquatable<IntPtr>, IParsable<IntPtr>, ISpanParsable<IntPtr>, IUtf8SpanParsable<IntPtr>, System::Numerics::IAdditionOperators<IntPtr, IntPtr, IntPtr>, System::Numerics::IAdditiveIdentity<IntPtr, IntPtr>, System::Numerics::IBinaryInteger<IntPtr>, System::Numerics::IBinaryNumber<IntPtr>, System::Numerics::IBitwiseOperators<IntPtr, IntPtr, IntPtr>, System::Numerics::IComparisonOperators<IntPtr, IntPtr, bool>, System::Numerics::IDecrementOperators<IntPtr>, System::Numerics::IDivisionOperators<IntPtr, IntPtr, IntPtr>, System::Numerics::IEqualityOperators<IntPtr, IntPtr, bool>, System::Numerics::IIncrementOperators<IntPtr>, System::Numerics::IMinMaxValue<IntPtr>, System::Numerics::IModulusOperators<IntPtr, IntPtr, IntPtr>, System::Numerics::IMultiplicativeIdentity<IntPtr, IntPtr>, System::Numerics::IMultiplyOperators<IntPtr, IntPtr, IntPtr>, System::Numerics::INumber<IntPtr>, System::Numerics::INumberBase<IntPtr>, System::Numerics::IShiftOperators<IntPtr, int, IntPtr>, System::Numerics::ISignedNumber<IntPtr>, System::Numerics::ISubtractionOperators<IntPtr, IntPtr, IntPtr>, System::Numerics::IUnaryNegationOperators<IntPtr, IntPtr>, System::Numerics::IUnaryPlusOperators<IntPtr, IntPtr>, 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 readonly struct IntPtr : IComparable, IComparable<IntPtr>, IEquatable<IntPtr>, IFormattable, System.Runtime.Serialization.ISerializable
public readonly struct IntPtr : IComparable, IComparable<IntPtr>, IEquatable<IntPtr>, ISpanFormattable, System.Runtime.Serialization.ISerializable
public readonly struct IntPtr : IComparable<IntPtr>, IEquatable<IntPtr>, IParsable<IntPtr>, ISpanParsable<IntPtr>, System.Numerics.IAdditionOperators<IntPtr,IntPtr,IntPtr>, System.Numerics.IAdditiveIdentity<IntPtr,IntPtr>, System.Numerics.IBinaryInteger<IntPtr>, System.Numerics.IBinaryNumber<IntPtr>, System.Numerics.IBitwiseOperators<IntPtr,IntPtr,IntPtr>, System.Numerics.IComparisonOperators<IntPtr,IntPtr,bool>, System.Numerics.IDecrementOperators<IntPtr>, System.Numerics.IDivisionOperators<IntPtr,IntPtr,IntPtr>, System.Numerics.IEqualityOperators<IntPtr,IntPtr,bool>, System.Numerics.IIncrementOperators<IntPtr>, System.Numerics.IMinMaxValue<IntPtr>, System.Numerics.IModulusOperators<IntPtr,IntPtr,IntPtr>, System.Numerics.IMultiplicativeIdentity<IntPtr,IntPtr>, System.Numerics.IMultiplyOperators<IntPtr,IntPtr,IntPtr>, System.Numerics.INumber<IntPtr>, System.Numerics.INumberBase<IntPtr>, System.Numerics.IShiftOperators<IntPtr,int,IntPtr>, System.Numerics.ISignedNumber<IntPtr>, System.Numerics.ISubtractionOperators<IntPtr,IntPtr,IntPtr>, System.Numerics.IUnaryNegationOperators<IntPtr,IntPtr>, System.Numerics.IUnaryPlusOperators<IntPtr,IntPtr>, System.Runtime.Serialization.ISerializable
public readonly struct IntPtr : IComparable<IntPtr>, IEquatable<IntPtr>, IParsable<IntPtr>, ISpanParsable<IntPtr>, IUtf8SpanParsable<IntPtr>, System.Numerics.IAdditionOperators<IntPtr,IntPtr,IntPtr>, System.Numerics.IAdditiveIdentity<IntPtr,IntPtr>, System.Numerics.IBinaryInteger<IntPtr>, System.Numerics.IBinaryNumber<IntPtr>, System.Numerics.IBitwiseOperators<IntPtr,IntPtr,IntPtr>, System.Numerics.IComparisonOperators<IntPtr,IntPtr,bool>, System.Numerics.IDecrementOperators<IntPtr>, System.Numerics.IDivisionOperators<IntPtr,IntPtr,IntPtr>, System.Numerics.IEqualityOperators<IntPtr,IntPtr,bool>, System.Numerics.IIncrementOperators<IntPtr>, System.Numerics.IMinMaxValue<IntPtr>, System.Numerics.IModulusOperators<IntPtr,IntPtr,IntPtr>, System.Numerics.IMultiplicativeIdentity<IntPtr,IntPtr>, System.Numerics.IMultiplyOperators<IntPtr,IntPtr,IntPtr>, System.Numerics.INumber<IntPtr>, System.Numerics.INumberBase<IntPtr>, System.Numerics.IShiftOperators<IntPtr,int,IntPtr>, System.Numerics.ISignedNumber<IntPtr>, System.Numerics.ISubtractionOperators<IntPtr,IntPtr,IntPtr>, System.Numerics.IUnaryNegationOperators<IntPtr,IntPtr>, System.Numerics.IUnaryPlusOperators<IntPtr,IntPtr>, System.Runtime.Serialization.ISerializable
public struct IntPtr : IEquatable<IntPtr>, System.Runtime.Serialization.ISerializable
public readonly 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 ISpanFormattable
    interface IFormattable
    interface ISerializable
type nativeint = struct
    interface IFormattable
    interface IParsable<nativeint>
    interface ISpanFormattable
    interface ISpanParsable<nativeint>
    interface IAdditionOperators<nativeint, nativeint, nativeint>
    interface IAdditiveIdentity<nativeint, nativeint>
    interface IBinaryInteger<nativeint>
    interface IBinaryNumber<nativeint>
    interface IBitwiseOperators<nativeint, nativeint, nativeint>
    interface IComparisonOperators<nativeint, nativeint, bool>
    interface IEqualityOperators<nativeint, nativeint, bool>
    interface IDecrementOperators<nativeint>
    interface IDivisionOperators<nativeint, nativeint, nativeint>
    interface IIncrementOperators<nativeint>
    interface IModulusOperators<nativeint, nativeint, nativeint>
    interface IMultiplicativeIdentity<nativeint, nativeint>
    interface IMultiplyOperators<nativeint, nativeint, nativeint>
    interface INumber<nativeint>
    interface INumberBase<nativeint>
    interface ISubtractionOperators<nativeint, nativeint, nativeint>
    interface IUnaryNegationOperators<nativeint, nativeint>
    interface IUnaryPlusOperators<nativeint, nativeint>
    interface IShiftOperators<nativeint, int, nativeint>
    interface IMinMaxValue<nativeint>
    interface ISignedNumber<nativeint>
    interface ISerializable
type nativeint = struct
    interface IFormattable
    interface IParsable<nativeint>
    interface ISpanFormattable
    interface ISpanParsable<nativeint>
    interface IAdditionOperators<nativeint, nativeint, nativeint>
    interface IAdditiveIdentity<nativeint, nativeint>
    interface IBinaryInteger<nativeint>
    interface IBinaryNumber<nativeint>
    interface IBitwiseOperators<nativeint, nativeint, nativeint>
    interface IComparisonOperators<nativeint, nativeint, bool>
    interface IEqualityOperators<nativeint, nativeint, bool>
    interface IDecrementOperators<nativeint>
    interface IDivisionOperators<nativeint, nativeint, nativeint>
    interface IIncrementOperators<nativeint>
    interface IModulusOperators<nativeint, nativeint, nativeint>
    interface IMultiplicativeIdentity<nativeint, nativeint>
    interface IMultiplyOperators<nativeint, nativeint, nativeint>
    interface INumber<nativeint>
    interface INumberBase<nativeint>
    interface ISubtractionOperators<nativeint, nativeint, nativeint>
    interface IUnaryNegationOperators<nativeint, nativeint>
    interface IUnaryPlusOperators<nativeint, nativeint>
    interface IUtf8SpanFormattable
    interface IUtf8SpanParsable<nativeint>
    interface IShiftOperators<nativeint, int, nativeint>
    interface IMinMaxValue<nativeint>
    interface ISignedNumber<nativeint>
    interface ISerializable
type nativeint = struct
    interface IFormattable
    interface IParsable<nativeint>
    interface ISpanFormattable
    interface ISpanParsable<nativeint>
    interface IUtf8SpanFormattable
    interface IUtf8SpanParsable<nativeint>
    interface IAdditionOperators<nativeint, nativeint, nativeint>
    interface IAdditiveIdentity<nativeint, nativeint>
    interface IBinaryInteger<nativeint>
    interface IBinaryNumber<nativeint>
    interface IBitwiseOperators<nativeint, nativeint, nativeint>
    interface IComparisonOperators<nativeint, nativeint, bool>
    interface IEqualityOperators<nativeint, nativeint, bool>
    interface IDecrementOperators<nativeint>
    interface IDivisionOperators<nativeint, nativeint, nativeint>
    interface IIncrementOperators<nativeint>
    interface IModulusOperators<nativeint, nativeint, nativeint>
    interface IMultiplicativeIdentity<nativeint, nativeint>
    interface IMultiplyOperators<nativeint, nativeint, nativeint>
    interface INumber<nativeint>
    interface INumberBase<nativeint>
    interface ISubtractionOperators<nativeint, nativeint, nativeint>
    interface IUnaryNegationOperators<nativeint, nativeint>
    interface IUnaryPlusOperators<nativeint, nativeint>
    interface IShiftOperators<nativeint, int, nativeint>
    interface IMinMaxValue<nativeint>
    interface ISignedNumber<nativeint>
    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 IComparable, IComparable(Of IntPtr), IEquatable(Of IntPtr), ISerializable, ISpanFormattable
Public Structure IntPtr
Implements IAdditionOperators(Of IntPtr, IntPtr, IntPtr), IAdditiveIdentity(Of IntPtr, IntPtr), IBinaryInteger(Of IntPtr), IBinaryNumber(Of IntPtr), IBitwiseOperators(Of IntPtr, IntPtr, IntPtr), IComparable(Of IntPtr), IComparisonOperators(Of IntPtr, IntPtr, Boolean), IDecrementOperators(Of IntPtr), IDivisionOperators(Of IntPtr, IntPtr, IntPtr), IEqualityOperators(Of IntPtr, IntPtr, Boolean), IEquatable(Of IntPtr), IIncrementOperators(Of IntPtr), IMinMaxValue(Of IntPtr), IModulusOperators(Of IntPtr, IntPtr, IntPtr), IMultiplicativeIdentity(Of IntPtr, IntPtr), IMultiplyOperators(Of IntPtr, IntPtr, IntPtr), INumber(Of IntPtr), INumberBase(Of IntPtr), IParsable(Of IntPtr), ISerializable, IShiftOperators(Of IntPtr, Integer, IntPtr), ISignedNumber(Of IntPtr), ISpanParsable(Of IntPtr), ISubtractionOperators(Of IntPtr, IntPtr, IntPtr), IUnaryNegationOperators(Of IntPtr, IntPtr), IUnaryPlusOperators(Of IntPtr, IntPtr)
Public Structure IntPtr
Implements IAdditionOperators(Of IntPtr, IntPtr, IntPtr), IAdditiveIdentity(Of IntPtr, IntPtr), IBinaryInteger(Of IntPtr), IBinaryNumber(Of IntPtr), IBitwiseOperators(Of IntPtr, IntPtr, IntPtr), IComparable(Of IntPtr), IComparisonOperators(Of IntPtr, IntPtr, Boolean), IDecrementOperators(Of IntPtr), IDivisionOperators(Of IntPtr, IntPtr, IntPtr), IEqualityOperators(Of IntPtr, IntPtr, Boolean), IEquatable(Of IntPtr), IIncrementOperators(Of IntPtr), IMinMaxValue(Of IntPtr), IModulusOperators(Of IntPtr, IntPtr, IntPtr), IMultiplicativeIdentity(Of IntPtr, IntPtr), IMultiplyOperators(Of IntPtr, IntPtr, IntPtr), INumber(Of IntPtr), INumberBase(Of IntPtr), IParsable(Of IntPtr), ISerializable, IShiftOperators(Of IntPtr, Integer, IntPtr), ISignedNumber(Of IntPtr), ISpanParsable(Of IntPtr), ISubtractionOperators(Of IntPtr, IntPtr, IntPtr), IUnaryNegationOperators(Of IntPtr, IntPtr), IUnaryPlusOperators(Of IntPtr, IntPtr), IUtf8SpanParsable(Of IntPtr)
Public Structure IntPtr
Implements IEquatable(Of IntPtr), ISerializable
Public Structure IntPtr
Implements ISerializable
Ereditarietà
IntPtr
Attributi
Implementazioni
IComparable IComparable<IntPtr> IEquatable<IntPtr> IFormattable ISerializable ISpanFormattable IComparable<TSelf> IEquatable<TSelf> IParsable<IntPtr> IParsable<TSelf> ISpanParsable<IntPtr> ISpanParsable<TSelf> IAdditionOperators<IntPtr,IntPtr,IntPtr> IAdditionOperators<TSelf,TSelf,TSelf> IAdditiveIdentity<IntPtr,IntPtr> IAdditiveIdentity<TSelf,TSelf> IBinaryInteger<IntPtr> IBinaryNumber<IntPtr> IBinaryNumber<TSelf> IBitwiseOperators<IntPtr,IntPtr,IntPtr> IBitwiseOperators<TSelf,TSelf,TSelf> IComparisonOperators<IntPtr,IntPtr,Boolean> IComparisonOperators<TSelf,TSelf,Boolean> IDecrementOperators<IntPtr> IDecrementOperators<TSelf> IDivisionOperators<IntPtr,IntPtr,IntPtr> IDivisionOperators<TSelf,TSelf,TSelf> IEqualityOperators<IntPtr,IntPtr,Boolean> IEqualityOperators<TSelf,TOther,TResult> IEqualityOperators<TSelf,TSelf,Boolean> IIncrementOperators<IntPtr> IIncrementOperators<TSelf> IMinMaxValue<IntPtr> IModulusOperators<IntPtr,IntPtr,IntPtr> IModulusOperators<TSelf,TSelf,TSelf> IMultiplicativeIdentity<IntPtr,IntPtr> IMultiplicativeIdentity<TSelf,TSelf> IMultiplyOperators<IntPtr,IntPtr,IntPtr> IMultiplyOperators<TSelf,TSelf,TSelf> INumber<IntPtr> INumber<TSelf> INumberBase<IntPtr> INumberBase<TSelf> IShiftOperators<IntPtr,Int32,IntPtr> IShiftOperators<TSelf,Int32,TSelf> ISignedNumber<IntPtr> ISubtractionOperators<IntPtr,IntPtr,IntPtr> ISubtractionOperators<TSelf,TSelf,TSelf> IUnaryNegationOperators<IntPtr,IntPtr> IUnaryNegationOperators<TSelf,TSelf> IUnaryPlusOperators<IntPtr,IntPtr> IUnaryPlusOperators<TSelf,TSelf> IUtf8SpanFormattable IUtf8SpanParsable<IntPtr> IUtf8SpanParsable<TSelf>

Esempio

Nell'esempio seguente vengono usati puntatori gestiti per invertire i caratteri in una matrice. Dopo l'inizializzazione di un String oggetto e la relativa lunghezza, esegue le operazioni seguenti:

  1. Chiama il Marshal.StringToHGlobalAnsi metodo per copiare la stringa Unicode nella memoria non gestita come carattere ANSI (un byte). Il metodo restituisce un IntPtr oggetto che punta all'inizio della stringa non gestita. Nell'esempio di Visual Basic viene utilizzato direttamente questo puntatore; negli esempi C++, F# e C# viene eseguito il cast a un puntatore a un byte.

  2. Chiama il Marshal.AllocHGlobal metodo per allocare lo stesso numero di byte occupato dalla stringa non gestita. Il metodo restituisce un IntPtr oggetto che punta all'inizio del blocco di memoria non gestito. Nell'esempio di Visual Basic viene utilizzato direttamente questo puntatore; negli esempi C++, F# e C# viene eseguito il cast a un puntatore a un byte.

  3. Nell'esempio di Visual Basic viene definita una variabile denominata offset uguale alla lunghezza della stringa ANSI. Viene usato per determinare l'offset in memoria non gestita in cui viene copiato il carattere successivo nella stringa ANSI. Poiché il valore iniziale è la lunghezza della stringa, l'operazione di copia copierà un carattere dall'inizio della stringa alla fine del blocco di memoria.

    Gli esempi C#, F# e C++ chiamano il ToPointer metodo per ottenere un puntatore non gestito all'indirizzo iniziale della stringa e al blocco di memoria non gestito e aggiungono uno minore della lunghezza della stringa all'indirizzo iniziale della stringa ANSI. Poiché il puntatore stringa non gestito punta ora alla fine della stringa, l'operazione di copia copierà un carattere dalla fine della stringa all'inizio del blocco di memoria.

  4. Usa un ciclo per copiare ogni carattere dalla stringa al blocco di memoria non gestito.

    Nell'esempio di Visual Basic viene chiamato il Marshal.ReadByte(IntPtr, Int32) metodo per leggere il byte (o un carattere a byte) in corrispondenza di un offset specificato dal puntatore gestito alla stringa ANSI. L'offset viene incrementato con ogni iterazione del ciclo. Chiama quindi il Marshal.WriteByte(IntPtr, Int32, Byte) metodo per scrivere il byte nell'indirizzo di memoria definito dall'indirizzo iniziale del blocco di memoria non gestito più offset. Quindi decrementa offset.

    Gli esempi C#, F# e C++ eseguono l'operazione di copia, quindi decrementare il puntatore all'indirizzo della posizione successiva nella stringa ANSI non gestita e incrementare il puntatore all'indirizzo successivo nel blocco non gestito.

  5. Tutti gli esempi chiamano per Marshal.PtrToStringAnsi convertire il blocco di memoria non gestito contenente la stringa ANSI copiata in un oggetto Unicode String gestito.

  6. Dopo aver visualizzato le stringhe originali e invertite, tutti gli esempi chiamano il FreeHGlobal metodo per liberare la memoria allocata per la stringa ANSI non gestita e il blocco di memoria non gestito.

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

Commenti

Il IntPtr tipo è progettato per essere un numero intero la cui dimensione è uguale a un puntatore. Ovvero, un'istanza di questo tipo dovrebbe essere a 32 bit in un processo a 32 bit e a 64 bit in un processo a 64 bit.

Il IntPtr tipo può essere usato dalle lingue che supportano puntatori e come mezzo comune per fare riferimento ai dati tra lingue che e non supportano puntatori.

IntPtr gli oggetti possono essere utilizzati anche per contenere handle. Ad esempio, le istanze di IntPtr vengono usate ampiamente nella System.IO.FileStream classe per contenere handle di file.

Nota

L'uso IntPtr come puntatore o handle è soggetto a errori e non sicuro. Si tratta semplicemente di un tipo integer che può essere usato come formato di interscambio per puntatori e handle a causa della stessa dimensione. Al di fuori dei requisiti di interscambio specifici, ad esempio per il passaggio di dati a un linguaggio che non supporta puntatori, è necessario usare un puntatore tipizzato correttamente per rappresentare i puntatori e SafeHandle deve essere usato per rappresentare gli handle.

Questo tipo implementa .ISerializable In .NET 5 e versioni successive questo tipo implementa anche le IFormattable interfacce. In .NET 7 e versioni successive questo tipo implementa anche le IBinaryInteger<TSelf>interfacce , IMinMaxValue<TSelf>e ISignedNumber<TSelf> .

In C# a partire dalla versione 9.0 è possibile usare il tipo predefinito nint per definire numeri interi di dimensioni native. Questo tipo è rappresentato dal IntPtr tipo internamente e fornisce operazioni e conversioni appropriate per i tipi integer. Per altre informazioni, vedere tipi nint e nuint.

In C# a partire dalla versione 11 e quando la destinazione è il runtime .NET 7 o versione successiva, nint è un alias per IntPtr nello stesso modo in cui int è un alias per Int32.

Costruttori

IntPtr(Int32)

Inizializza una nuova istanza di IntPtr usando l'intero con segno a 32 bit specificato.

IntPtr(Int64)

Inizializza una nuova istanza di IntPtr usando l'intero con segno a 64 bit specificato.

IntPtr(Void*)

Inizializza una nuova istanza di IntPtr usando il puntatore specificato a un tipo non specificato.

Campi

Zero

Campo di sola lettura che rappresenta un intero con segno inizializzato su zero.

Proprietà

MaxValue

Ottiene il valore più grande possibile di IntPtr.

MinValue

Ottiene il valore più piccolo possibile di IntPtr.

Size

Ottiene le dimensioni dell'istanza.

Metodi

Abs(IntPtr)

Calcola l'assoluto di un valore.

Add(IntPtr, Int32)

Aggiunge un offset a un intero con segno.

Clamp(IntPtr, IntPtr, IntPtr)

Blocca un valore a un valore minimo e massimo inclusivo.

CompareTo(IntPtr)

Confronta l'istanza corrente con un altro oggetto dello stesso tipo e restituisce un intero che indica se l'istanza corrente precede, segue o si trova nella stessa posizione dell'altro oggetto all'interno dell'ordinamento.

CompareTo(Object)

Confronta l'istanza corrente con un altro oggetto dello stesso tipo e restituisce un intero che indica se l'istanza corrente precede, segue o si trova nella stessa posizione dell'altro oggetto all'interno dell'ordinamento.

CopySign(IntPtr, IntPtr)

Copia il segno di un valore nel segno di un altro valore.

CreateChecked<TOther>(TOther)

Crea un'istanza del tipo corrente da un valore, generando un'eccezione di overflow per tutti i valori che rientrano all'esterno dell'intervallo rappresentabile del tipo corrente.

CreateSaturating<TOther>(TOther)

Crea un'istanza del tipo corrente da un valore, saturazione di tutti i valori che rientrano all'esterno dell'intervallo rappresentabile del tipo corrente.

CreateTruncating<TOther>(TOther)

Crea un'istanza del tipo corrente da un valore, troncando tutti i valori che rientrano all'esterno dell'intervallo rappresentabile del tipo corrente.

DivRem(IntPtr, IntPtr)

Calcola il quoziente e il resto di due valori.

Equals(IntPtr)

Indica se l'oggetto corrente è uguale a un altro oggetto dello stesso tipo.

Equals(Object)

Restituisce un valore che indica se questa istanza è uguale a un oggetto specificato.

GetHashCode()

Restituisce il codice hash per l'istanza.

IsEvenInteger(IntPtr)

Determina se un valore rappresenta un numero integrale pari.

IsNegative(IntPtr)

Determina se un valore è negativo.

IsOddInteger(IntPtr)

Determina se un valore rappresenta un numero integrale dispari.

IsPositive(IntPtr)

Determina se un valore è positivo.

IsPow2(IntPtr)

Determina se un valore è una potenza di due.

LeadingZeroCount(IntPtr)

Calcola il numero di zero iniziali in un valore.

Log2(IntPtr)

Calcola il log2 di un valore.

Max(IntPtr, IntPtr)

Confronta due valori per calcolare che è maggiore.

MaxMagnitude(IntPtr, IntPtr)

Confronta due valori per calcolare che è maggiore.

Min(IntPtr, IntPtr)

Confronta due valori per calcolare che è minore.

MinMagnitude(IntPtr, IntPtr)

Confronta due valori per calcolare che è minore.

Parse(ReadOnlySpan<Byte>, IFormatProvider)

Analizza un intervallo di caratteri UTF-8 in un valore.

Parse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider)

Analizza un intervallo di caratteri UTF-8 in un valore.

Parse(ReadOnlySpan<Char>, IFormatProvider)

Analizza un intervallo di caratteri in un valore.

Parse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider)

Converte l'intervallo di caratteri di sola lettura di un numero in un formato specifico dello stile e delle impostazioni cultura specificato nell'intero nativo firmato equivalente.

Parse(String)

Converte la rappresentazione di stringa di un numero nell'intero nativo con segno equivalente.

Parse(String, IFormatProvider)

Converte la rappresentazione stringa di un numero in un formato specifico delle impostazioni cultura specificato nell'intero nativo firmato equivalente.

Parse(String, NumberStyles)

Converte la rappresentazione di stringa di un numero in uno stile specificato nell'equivalente intero con segno a 64 bit.

Parse(String, NumberStyles, IFormatProvider)

Converte la rappresentazione di stringa di un numero in uno stile e un formato delle impostazioni cultura specifici nell'equivalente intero nativo con segno.

PopCount(IntPtr)

Calcola il numero di bit impostati in un valore.

RotateLeft(IntPtr, Int32)

Ruota un valore sinistro da una determinata quantità.

RotateRight(IntPtr, Int32)

Ruota un valore a destra in base a una determinata quantità.

Sign(IntPtr)

Calcola il segno di un valore.

Subtract(IntPtr, Int32)

Sottrae un offset da un intero firmato.

ToInt32()

Converte il valore dell'istanza in un intero con segno a 32 bit.

ToInt64()

Converte il valore dell'istanza in un intero con segno a 64 bit.

ToPointer()

Converte il valore dell'istanza in un puntatore a un tipo non specificato.

ToString()

Converte il valore numerico dell'oggetto IntPtr corrente nella rappresentazione di stringa equivalente.

ToString(IFormatProvider)

Converte il valore numerico dell'istanza nella rappresentazione di stringa equivalente usando il formato specificato e le informazioni di formattazione specifiche delle impostazioni cultura.

ToString(String)

Converte il valore numerico dell'oggetto IntPtr corrente nella rappresentazione di stringa equivalente.

ToString(String, IFormatProvider)

Formatta il valore dell'istanza corrente usando il formato specificato.

TrailingZeroCount(IntPtr)

Calcola il numero di zeri finali in un valore.

TryFormat(Span<Byte>, Int32, ReadOnlySpan<Char>, IFormatProvider)

Tenta di formattare il valore dell'istanza corrente come UTF-8 nell'intervallo di byte specificato.

TryFormat(Span<Char>, Int32, ReadOnlySpan<Char>, IFormatProvider)

Tenta di formattare il valore dell'istanza corrente nell'intervallo di caratteri specificato.

TryParse(ReadOnlySpan<Byte>, IFormatProvider, IntPtr)

Tenta di analizzare un intervallo di caratteri UTF-8 in un valore.

TryParse(ReadOnlySpan<Byte>, IntPtr)

Tenta di convertire un intervallo di caratteri UTF-8 contenente la rappresentazione di stringa di un numero nell'equivalente intero con segno.

TryParse(ReadOnlySpan<Byte>, NumberStyles, IFormatProvider, IntPtr)

Tenta di analizzare un intervallo di caratteri UTF-8 in un valore.

TryParse(ReadOnlySpan<Char>, IFormatProvider, IntPtr)

Tenta di analizzare una stringa in un valore.

TryParse(ReadOnlySpan<Char>, IntPtr)

Converte l'intervallo di caratteri di sola lettura di un numero nell'equivalente intero nativo con segno. Un valore restituito indica se la conversione è riuscita.

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, IntPtr)

Converte l'intervallo di sola lettura della rappresentazione di caratteri di un numero in uno stile e un formato specifico delle impostazioni cultura specificati nell'equivalente intero nativo con segno. Un valore restituito indica se la conversione è riuscita.

TryParse(String, IFormatProvider, IntPtr)

Tenta di analizzare una stringa in un valore.

TryParse(String, IntPtr)

Converte la rappresentazione di stringa di un numero nell'intero nativo con segno equivalente. Un valore restituito indica se la conversione è riuscita.

TryParse(String, NumberStyles, IFormatProvider, IntPtr)

Converte la rappresentazione di stringa di un numero in uno stile e un formato delle impostazioni cultura specifici nell'equivalente intero nativo con segno. Un valore restituito indica se la conversione è riuscita.

Operatori

Addition(IntPtr, Int32)

Aggiunge un offset a un intero con segno.

Equality(IntPtr, IntPtr)

Determina se due istanze specificate dell'oggetto IntPtr sono uguali.

Explicit(Int32 to IntPtr)

Converte il valore di un intero con segno a 32 bit in un tipo IntPtr.

Explicit(Int64 to IntPtr)

Converte il valore di un intero con segno a 64 bit in un tipo IntPtr.

Explicit(IntPtr to Int32)

Converte il valore dell'oggetto IntPtr specificato in un intero con segno a 32 bit.

Explicit(IntPtr to Int64)

Converte il valore dell'oggetto IntPtr specificato in un intero con segno a 64 bit.

Explicit(IntPtr to Void*)

Converte il valore dell'oggetto IntPtr specificato in un puntatore a un tipo non specificato.

Questa API non è conforme a CLS.

Explicit(Void* to IntPtr)

Converte il puntatore specificato per un tipo non specificato in un oggetto IntPtr.

Questa API non è conforme a CLS.

Inequality(IntPtr, IntPtr)

Determina se due istanze specificate dell'oggetto IntPtr non sono uguali.

Subtraction(IntPtr, Int32)

Sottrae un offset da un intero firmato.

Implementazioni dell'interfaccia esplicita

IAdditionOperators<IntPtr,IntPtr,IntPtr>.Addition(IntPtr, IntPtr)

Aggiunge due valori insieme per calcolare la somma.

IAdditionOperators<IntPtr,IntPtr,IntPtr>.CheckedAddition(IntPtr, IntPtr)

Aggiunge due valori insieme per calcolare la somma.

IAdditiveIdentity<IntPtr,IntPtr>.AdditiveIdentity

Ottiene l'identità additiva del tipo corrente.

IBinaryInteger<IntPtr>.GetByteCount()

Ottiene il numero di byte che verranno scritti come parte di TryWriteLittleEndian(Span<Byte>, Int32).

IBinaryInteger<IntPtr>.GetShortestBitLength()

Ottiene la lunghezza, in bit, della rappresentazione di complemento più breve del valore corrente.

IBinaryInteger<IntPtr>.TryReadBigEndian(ReadOnlySpan<Byte>, Boolean, IntPtr)

Rappresenta un intero con segno in cui la larghezza del bit è uguale a un puntatore.

IBinaryInteger<IntPtr>.TryReadLittleEndian(ReadOnlySpan<Byte>, Boolean, IntPtr)

Rappresenta un intero con segno in cui la larghezza del bit è uguale a un puntatore.

IBinaryInteger<IntPtr>.TryWriteBigEndian(Span<Byte>, Int32)

Prova a scrivere il valore corrente, in formato big-endian, in un determinato intervallo.

IBinaryInteger<IntPtr>.TryWriteLittleEndian(Span<Byte>, Int32)

Tenta di scrivere il valore corrente, in formato little-endian, in un determinato intervallo.

IBinaryNumber<IntPtr>.AllBitsSet

Ottiene un'istanza del tipo binario in cui vengono impostati tutti i bit.

IBitwiseOperators<IntPtr,IntPtr,IntPtr>.BitwiseAnd(IntPtr, IntPtr)

Calcola i valori bit per bit e di due valori.

IBitwiseOperators<IntPtr,IntPtr,IntPtr>.BitwiseOr(IntPtr, IntPtr)

Calcola i valori bit per bit o di due valori.

IBitwiseOperators<IntPtr,IntPtr,IntPtr>.ExclusiveOr(IntPtr, IntPtr)

Calcola l'esclusivo o di due valori.

IBitwiseOperators<IntPtr,IntPtr,IntPtr>.OnesComplement(IntPtr)

Calcola la rappresentazione di complemento di un determinato valore.

IComparisonOperators<IntPtr,IntPtr,Boolean>.GreaterThan(IntPtr, IntPtr)

Confronta due valori per determinare quale è maggiore.

IComparisonOperators<IntPtr,IntPtr,Boolean>.GreaterThanOrEqual(IntPtr, IntPtr)

Confronta due valori per determinare quale è maggiore o uguale.

IComparisonOperators<IntPtr,IntPtr,Boolean>.LessThan(IntPtr, IntPtr)

Confronta due valori per determinare quali sono meno.

IComparisonOperators<IntPtr,IntPtr,Boolean>.LessThanOrEqual(IntPtr, IntPtr)

Confronta due valori per determinare quale è minore o uguale.

IDecrementOperators<IntPtr>.CheckedDecrement(IntPtr)

Decrementa un valore.

IDecrementOperators<IntPtr>.Decrement(IntPtr)

Decrementa un valore.

IDivisionOperators<IntPtr,IntPtr,IntPtr>.Division(IntPtr, IntPtr)

Divide un valore da un altro per calcolare il quoziente.

IEquatable<IntPtr>.Equals(IntPtr)

Restituisce un valore che indica se questa istanza è uguale a un altro intero firmato.

IIncrementOperators<IntPtr>.CheckedIncrement(IntPtr)

Incrementa un valore.

IIncrementOperators<IntPtr>.Increment(IntPtr)

Incrementa un valore.

IMinMaxValue<IntPtr>.MaxValue

Ottiene il valore massimo del tipo corrente.

IMinMaxValue<IntPtr>.MinValue

Ottiene il valore minimo del tipo corrente.

IModulusOperators<IntPtr,IntPtr,IntPtr>.Modulus(IntPtr, IntPtr)

Divide due valori insieme per calcolare il modulo o il resto.

IMultiplicativeIdentity<IntPtr,IntPtr>.MultiplicativeIdentity

Ottiene l'identità moltiplicativa del tipo corrente.

IMultiplyOperators<IntPtr,IntPtr,IntPtr>.CheckedMultiply(IntPtr, IntPtr)

Moltiplica due valori insieme per calcolare il prodotto.

IMultiplyOperators<IntPtr,IntPtr,IntPtr>.Multiply(IntPtr, IntPtr)

Moltiplica due valori insieme per calcolare il prodotto.

INumber<IntPtr>.MaxNumber(IntPtr, IntPtr)

Confronta due valori per calcolare che è maggiore e restituisce l'altro valore se un input è NaN.

INumber<IntPtr>.MinNumber(IntPtr, IntPtr)

Confronta due valori per calcolare che è minore e restituisce l'altro valore se un input è NaN.

INumberBase<IntPtr>.IsCanonical(IntPtr)

Determina se un valore è nella relativa rappresentazione canonica.

INumberBase<IntPtr>.IsComplexNumber(IntPtr)

Determina se un valore rappresenta un numero complesso.

INumberBase<IntPtr>.IsFinite(IntPtr)

Determina se un valore è finito.

INumberBase<IntPtr>.IsImaginaryNumber(IntPtr)

Determina se un valore rappresenta un numero immaginario puro.

INumberBase<IntPtr>.IsInfinity(IntPtr)

Determina se un valore è infinito.

INumberBase<IntPtr>.IsInteger(IntPtr)

Determina se un valore rappresenta un numero integrale.

INumberBase<IntPtr>.IsNaN(IntPtr)

Determina se un valore è NaN.

INumberBase<IntPtr>.IsNegativeInfinity(IntPtr)

Determina se un valore è infinito negativo.

INumberBase<IntPtr>.IsNormal(IntPtr)

Determina se un valore è normale.

INumberBase<IntPtr>.IsPositiveInfinity(IntPtr)

Determina se un valore è infinito positivo.

INumberBase<IntPtr>.IsRealNumber(IntPtr)

Determina se un valore rappresenta un numero reale.

INumberBase<IntPtr>.IsSubnormal(IntPtr)

Determina se un valore è subnormal.

INumberBase<IntPtr>.IsZero(IntPtr)

Determina se un valore è zero.

INumberBase<IntPtr>.MaxMagnitudeNumber(IntPtr, IntPtr)

Confronta due valori con il calcolo che ha la grandezza maggiore e restituisce l'altro valore se un input è NaN.

INumberBase<IntPtr>.MinMagnitudeNumber(IntPtr, IntPtr)

Confronta due valori con il calcolo con la grandezza minore e restituendo l'altro valore se un input è NaN.

INumberBase<IntPtr>.One

Ottiene il valore 1 per il tipo.

INumberBase<IntPtr>.Radix

Ottiene il radix, o base, per il tipo .

INumberBase<IntPtr>.TryConvertFromChecked<TOther>(TOther, IntPtr)

Rappresenta un intero con segno in cui la larghezza del bit è uguale a un puntatore.

INumberBase<IntPtr>.TryConvertFromSaturating<TOther>(TOther, IntPtr)

Rappresenta un intero con segno in cui la larghezza del bit è uguale a un puntatore.

INumberBase<IntPtr>.TryConvertFromTruncating<TOther>(TOther, IntPtr)

Rappresenta un intero con segno in cui la larghezza del bit è uguale a un puntatore.

INumberBase<IntPtr>.TryConvertToChecked<TOther>(IntPtr, TOther)

Tenta di convertire un'istanza del tipo corrente in un altro tipo, generando un'eccezione di overflow per tutti i valori che non rientrano nell'intervallo rappresentabile del tipo corrente.

INumberBase<IntPtr>.TryConvertToSaturating<TOther>(IntPtr, TOther)

Tenta di convertire un'istanza del tipo corrente in un altro tipo, saturazione di tutti i valori che non rientrano nell'intervallo rappresentabile del tipo corrente.

INumberBase<IntPtr>.TryConvertToTruncating<TOther>(IntPtr, TOther)

Tenta di convertire un'istanza del tipo corrente in un altro tipo, troncando tutti i valori che non rientrano nell'intervallo rappresentabile del tipo corrente.

INumberBase<IntPtr>.Zero

Ottiene il valore 0 per il tipo.

ISerializable.GetObjectData(SerializationInfo, StreamingContext)

Compila un oggetto SerializationInfo con i dati necessari per serializzare l'oggetto IntPtr corrente.

IShiftOperators<IntPtr,Int32,IntPtr>.LeftShift(IntPtr, Int32)

Sposta un valore lasciato da un determinato importo.

IShiftOperators<IntPtr,Int32,IntPtr>.RightShift(IntPtr, Int32)

Sposta un valore a destra in base a una determinata quantità.

IShiftOperators<IntPtr,Int32,IntPtr>.UnsignedRightShift(IntPtr, Int32)

Sposta un valore a destra in base a una determinata quantità.

ISignedNumber<IntPtr>.NegativeOne

Ottiene il valore -1 per il tipo.

ISubtractionOperators<IntPtr,IntPtr,IntPtr>.CheckedSubtraction(IntPtr, IntPtr)

Sottrae due valori per calcolare la differenza.

ISubtractionOperators<IntPtr,IntPtr,IntPtr>.Subtraction(IntPtr, IntPtr)

Sottrae due valori per calcolare la differenza.

IUnaryNegationOperators<IntPtr,IntPtr>.CheckedUnaryNegation(IntPtr)

Calcola la negazione unaria controllata di un valore.

IUnaryNegationOperators<IntPtr,IntPtr>.UnaryNegation(IntPtr)

Calcola la negazione unaria di un valore.

IUnaryPlusOperators<IntPtr,IntPtr>.UnaryPlus(IntPtr)

Calcola il segno più unario di un valore.

Si applica a

Thread safety

Questo tipo è thread-safe.

Vedi anche