Marshal.PtrToStructure Metodo

Definizione

Effettua il marshalling di dati da un blocco di memoria non gestita a un oggetto gestito.

Overload

PtrToStructure(IntPtr, Object)
Obsoleti.

Effettua il marshalling di dati da un blocco di memoria non gestita a un oggetto gestito.

PtrToStructure(IntPtr, Type)
Obsoleti.

Effettua il marshalling di dati da un blocco di memoria non gestita a un oggetto gestito appena allocato del tipo specificato.

PtrToStructure<T>(IntPtr)

Effettua il marshalling di dati da un blocco di memoria non gestita a un oggetto gestito appena allocato del tipo specificato per un parametro del tipo generico.

PtrToStructure<T>(IntPtr, T)

Effettua il marshalling di dati da un blocco di memoria non gestita a un oggetto gestito di un tipo specificato.

PtrToStructure(IntPtr, Object)

Source:
Marshal.cs
Source:
Marshal.cs
Source:
Marshal.cs

Attenzione

PtrToStructure(IntPtr, Object) may be unavailable in future releases. Instead, use PtrToStructure<T>(IntPtr). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296512

Effettua il marshalling di dati da un blocco di memoria non gestita a un oggetto gestito.

public:
 static void PtrToStructure(IntPtr ptr, System::Object ^ structure);
[System.Obsolete("PtrToStructure(IntPtr, Object) may be unavailable in future releases. Instead, use PtrToStructure<T>(IntPtr). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296512")]
[System.Security.SecurityCritical]
public static void PtrToStructure (IntPtr ptr, object structure);
public static void PtrToStructure (IntPtr ptr, object structure);
[System.Security.SecurityCritical]
public static void PtrToStructure (IntPtr ptr, object structure);
[System.Runtime.InteropServices.ComVisible(true)]
public static void PtrToStructure (IntPtr ptr, object structure);
[System.Security.SecurityCritical]
[System.Runtime.InteropServices.ComVisible(true)]
public static void PtrToStructure (IntPtr ptr, object structure);
[<System.Obsolete("PtrToStructure(IntPtr, Object) may be unavailable in future releases. Instead, use PtrToStructure<T>(IntPtr). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296512")>]
[<System.Security.SecurityCritical>]
static member PtrToStructure : nativeint * obj -> unit
static member PtrToStructure : nativeint * obj -> unit
[<System.Security.SecurityCritical>]
static member PtrToStructure : nativeint * obj -> unit
[<System.Runtime.InteropServices.ComVisible(true)>]
static member PtrToStructure : nativeint * obj -> unit
[<System.Security.SecurityCritical>]
[<System.Runtime.InteropServices.ComVisible(true)>]
static member PtrToStructure : nativeint * obj -> unit
Public Shared Sub PtrToStructure (ptr As IntPtr, structure As Object)

Parametri

ptr
IntPtr

nativeint

Puntatore a un blocco di memoria non gestita.

structure
Object

Oggetto nel quale devono essere copiati i dati. Deve essere un'istanza di una classe formattata.

Attributi

Eccezioni

Il layout della struttura non è sequenziale o esplicito.

-oppure-

La struttura è un tipo valore boxed.

Commenti

PtrToStructure è spesso necessario nell'interoperabilità COM e nella piattaforma invoke quando i parametri della struttura sono rappresentati come System.IntPtr valore. Non è possibile utilizzare questo metodo di overload con tipi valore. Se il ptr parametro è uguale IntPtr.Zeroa , null verrà restituito .

Si applica a

PtrToStructure(IntPtr, Type)

Source:
Marshal.cs
Source:
Marshal.cs
Source:
Marshal.cs

Attenzione

PtrToStructure(IntPtr, Type) may be unavailable in future releases. Instead, use PtrToStructure<T>(IntPtr). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296513

Effettua il marshalling di dati da un blocco di memoria non gestita a un oggetto gestito appena allocato del tipo specificato.

public:
 static System::Object ^ PtrToStructure(IntPtr ptr, Type ^ structureType);
[System.Obsolete("PtrToStructure(IntPtr, Type) may be unavailable in future releases. Instead, use PtrToStructure<T>(IntPtr). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296513")]
[System.Security.SecurityCritical]
public static object PtrToStructure (IntPtr ptr, Type structureType);
public static object? PtrToStructure (IntPtr ptr, Type structureType);
[System.Security.SecurityCritical]
public static object PtrToStructure (IntPtr ptr, Type structureType);
public static object PtrToStructure (IntPtr ptr, Type structureType);
[System.Runtime.InteropServices.ComVisible(true)]
public static object PtrToStructure (IntPtr ptr, Type structureType);
[System.Security.SecurityCritical]
[System.Runtime.InteropServices.ComVisible(true)]
public static object PtrToStructure (IntPtr ptr, Type structureType);
[<System.Obsolete("PtrToStructure(IntPtr, Type) may be unavailable in future releases. Instead, use PtrToStructure<T>(IntPtr). For more info, go to http://go.microsoft.com/fwlink/?LinkID=296513")>]
[<System.Security.SecurityCritical>]
static member PtrToStructure : nativeint * Type -> obj
static member PtrToStructure : nativeint * Type -> obj
[<System.Security.SecurityCritical>]
static member PtrToStructure : nativeint * Type -> obj
[<System.Runtime.InteropServices.ComVisible(true)>]
static member PtrToStructure : nativeint * Type -> obj
[<System.Security.SecurityCritical>]
[<System.Runtime.InteropServices.ComVisible(true)>]
static member PtrToStructure : nativeint * Type -> obj
Public Shared Function PtrToStructure (ptr As IntPtr, structureType As Type) As Object

Parametri

ptr
IntPtr

nativeint

Puntatore a un blocco di memoria non gestita.

structureType
Type

Tipo di oggetto da creare. Questo oggetto deve rappresentare una classe formattata o una struttura.

Restituisce

Oggetto gestito contenente i dati a cui punta il parametro ptr.

Attributi

Eccezioni

Il layout del parametro structureType non è sequenziale o esplicito.

-oppure-

Il parametro structureType è una definizione di tipo generico.

structureType è null.

La classe specificata da structureType non ha un costruttore senza parametri accessibile.

Esempio

L'esempio seguente crea una struttura gestita, la trasferisce alla memoria non gestita e quindi la trasferisce nuovamente alla memoria gestita usando il PtrToStructure metodo .

using System;
using System.Runtime.InteropServices;

public struct Point
{
    public int x;
    public int y;
}

class Example
{

    static void Main()
    {

        // Create a point struct.
        Point p;
        p.x = 1;
        p.y = 1;

        Console.WriteLine("The value of first point is " + p.x + " and " + p.y + ".");

        // Initialize unmanged memory to hold the struct.
        IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(p));

        try
        {

            // Copy the struct to unmanaged memory.
            Marshal.StructureToPtr(p, pnt, false);

            // Create another point.
            Point anotherP;

            // Set this Point to the value of the
            // Point in unmanaged memory.
            anotherP = (Point)Marshal.PtrToStructure(pnt, typeof(Point));

            Console.WriteLine("The value of new point is " + anotherP.x + " and " + anotherP.y + ".");
        }
        finally
        {
            // Free the unmanaged memory.
            Marshal.FreeHGlobal(pnt);
        }
    }
}
Imports System.Runtime.InteropServices



Public Structure Point
    Public x As Integer
    Public y As Integer
End Structure


Module Example


    Sub Main()

        ' Create a point struct.
        Dim p As Point
        p.x = 1
        p.y = 1

        Console.WriteLine("The value of first point is " + p.x.ToString + " and " + p.y.ToString + ".")

        ' Initialize unmanged memory to hold the struct.
        Dim pnt As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(p))

        Try

            ' Copy the struct to unmanaged memory.
            Marshal.StructureToPtr(p, pnt, False)

            ' Create another point.
            Dim anotherP As Point

            ' Set this Point to the value of the 
            ' Point in unmanaged memory. 
            anotherP = CType(Marshal.PtrToStructure(pnt, GetType(Point)), Point)

            Console.WriteLine("The value of new point is " + anotherP.x.ToString + " and " + anotherP.y.ToString + ".")

        Finally
            ' Free the unmanaged memory.
            Marshal.FreeHGlobal(pnt)
        End Try

    End Sub
End Module

Nell'esempio seguente viene illustrato come effettuare il marshalling di un blocco di memoria non gestito in una struttura gestita usando il PtrToStructure metodo .

Importante

Questo codice presuppone la compilazione a 32 bit. Prima di usare un compilatore a 64 bit, sostituire IntPtr.ToInt32 con IntPtr.ToInt64.

[StructLayout(LayoutKind::Sequential)]
ref class INNER
{
public:
    [MarshalAs(UnmanagedType::ByValTStr,SizeConst=10)]
    String^ field;

    INNER()
    {
        field = "Test";
    }
};

[StructLayout(LayoutKind::Sequential)]
value struct OUTER
{
public:
    [MarshalAs(UnmanagedType::ByValTStr,SizeConst=10)]
    String^ field;

    [MarshalAs(UnmanagedType::ByValArray,SizeConst=100)]
    array<Byte>^ inner;
};

[DllImport("SomeTestDLL.dll")]
static void CallTest(OUTER^ outerStructurePointer);

void static Work()
{
    OUTER outerStructure;
    array<INNER^>^ innerArray = gcnew array<INNER^>(10);
    INNER^ innerStructure = gcnew INNER;
    int structSize = Marshal::SizeOf(innerStructure);
    int size = innerArray->Length * structSize;
    outerStructure.inner = gcnew array<Byte>(size);

    try
    {
        CallTest(outerStructure);
    }
    catch (SystemException^ ex) 
    {
        Console::WriteLine(ex->Message);
    }

    IntPtr buffer = Marshal::AllocCoTaskMem(structSize * 10);
    Marshal::Copy(outerStructure.inner, 0, buffer, structSize * 10);
    int currentOffset = 0;
    for (int i = 0; i < 10; i++)
    {
        innerArray[i] = safe_cast<INNER^>(Marshal::PtrToStructure(
            IntPtr(buffer.ToInt32() + currentOffset),
            INNER::typeid));
        currentOffset += structSize;
    }
    Console::WriteLine(outerStructure.field);
    Marshal::FreeCoTaskMem(buffer);
}

        [StructLayout(LayoutKind.Sequential)]

        public class  INNER

        {

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst =  10)]

            public string field1 = "Test";
        }	

        [StructLayout(LayoutKind.Sequential)]

        public struct OUTER

        {

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst =  10)]

            public string field1;

            [MarshalAs(UnmanagedType.ByValArray, SizeConst =  100)]

            public byte[] inner;
        }
        [DllImport(@"SomeTestDLL.dll")]

        public static extern void CallTest( ref OUTER po);
        static void Main(string[] args)

        {

            OUTER ed = new OUTER();

            INNER[] inn=new INNER[10];

            INNER test = new INNER();

            int iStructSize = Marshal.SizeOf(test);
            int sz =inn.Length * iStructSize;

            ed.inner = new byte[sz];
            try

            {

                CallTest( ref ed);
            }

            catch(Exception e)

            {

                Console.WriteLine(e.Message);
            }

            IntPtr buffer = Marshal.AllocCoTaskMem(iStructSize*10);

            Marshal.Copy(ed.inner,0,buffer,iStructSize*10);
            int iCurOffset = 0;

            for(int i=0;i<10;i++)

            {
                inn[i] = (INNER)Marshal.PtrToStructure(new
IntPtr(buffer.ToInt32()+iCurOffset),typeof(INNER) );

                iCurOffset += iStructSize;
            }

            Console.WriteLine(ed.field1);

            Marshal.FreeCoTaskMem(buffer);
        }

Commenti

PtrToStructure è spesso necessario nell'interoperabilità COM e nella piattaforma invoke quando i parametri della struttura sono rappresentati come System.IntPtr valore. È possibile passare un tipo valore a questo metodo di overload. In questo caso, l'oggetto restituito è un'istanza boxed. Se il ptr parametro è uguale IntPtr.Zeroa , null verrà restituito .

Vedi anche

Si applica a

PtrToStructure<T>(IntPtr)

Source:
Marshal.cs
Source:
Marshal.cs
Source:
Marshal.cs

Effettua il marshalling di dati da un blocco di memoria non gestita a un oggetto gestito appena allocato del tipo specificato per un parametro del tipo generico.

public:
generic <typename T>
 static T PtrToStructure(IntPtr ptr);
[System.Security.SecurityCritical]
public static T PtrToStructure<T> (IntPtr ptr);
public static T? PtrToStructure<T> (IntPtr ptr);
public static T PtrToStructure<T> (IntPtr ptr);
[<System.Security.SecurityCritical>]
static member PtrToStructure : nativeint -> 'T
static member PtrToStructure : nativeint -> 'T
Public Shared Function PtrToStructure(Of T) (ptr As IntPtr) As T

Parametri di tipo

T

Tipo dell'oggetto nel quale devono essere copiati i dati. Questo deve rappresentare una classe formattata o una struttura.

Parametri

ptr
IntPtr

nativeint

Puntatore a un blocco di memoria non gestita.

Restituisce

T

Oggetto gestito che contiene i dati a cui punta il parametro ptr.

Attributi

Eccezioni

Il layout di T non è sequenziale o esplicito.

La classe specificata da T non ha un costruttore senza parametri accessibile.

Commenti

PtrToStructure<T>(IntPtr) è spesso necessario nell'interoperabilità COM e nella piattaforma invoke quando i parametri della struttura sono rappresentati come System.IntPtr valori. È possibile passare un tipo valore a questo overload del metodo. Se il ptr parametro è uguale a IntPtr.Zero e T è un tipo riferimento, null viene restituito . Se ptr è uguale a IntPtr.Zero e T è un tipo di valore, viene generata un'eccezione NullReferenceException .

Si applica a

PtrToStructure<T>(IntPtr, T)

Source:
Marshal.cs
Source:
Marshal.cs
Source:
Marshal.cs

Effettua il marshalling di dati da un blocco di memoria non gestita a un oggetto gestito di un tipo specificato.

public:
generic <typename T>
 static void PtrToStructure(IntPtr ptr, T structure);
[System.Security.SecurityCritical]
public static void PtrToStructure<T> (IntPtr ptr, T structure);
public static void PtrToStructure<T> (IntPtr ptr, T structure);
[<System.Security.SecurityCritical>]
static member PtrToStructure : nativeint * 'T -> unit
static member PtrToStructure : nativeint * 'T -> unit
Public Shared Sub PtrToStructure(Of T) (ptr As IntPtr, structure As T)

Parametri di tipo

T

Tipo di structure. Deve essere una classe formattata.

Parametri

ptr
IntPtr

nativeint

Puntatore a un blocco di memoria non gestita.

structure
T

Oggetto nel quale devono essere copiati i dati.

Attributi

Eccezioni

Il layout della struttura non è sequenziale o esplicito.

Commenti

PtrToStructure<T>(IntPtr, T) è spesso necessario nell'interoperabilità COM e nella piattaforma invoke quando i parametri della struttura sono rappresentati come IntPtr valori. Non è possibile utilizzare questo overload del metodo con tipi valore. Se il ptr parametro è uguale a IntPtr.Zero e T è un tipo riferimento, null viene restituito . Se ptr è uguale a IntPtr.Zero e T è un tipo di valore, viene generata un'eccezione NullReferenceException .

Si applica a