Marshal.PtrToStructure Método

Definición

Calcula las referencias a los datos desde un bloque de memoria no administrada a un objeto administrado.

Sobrecargas

PtrToStructure(IntPtr, Object)
Obsoletos.

Calcula las referencias a los datos desde un bloque de memoria no administrada a un objeto administrado.

PtrToStructure(IntPtr, Type)
Obsoletos.

Calcula las referencias a los datos desde un bloque de memoria no administrado a un objeto administrado y recién asignado del tipo especificado.

PtrToStructure<T>(IntPtr)

Serializa las referencias a los datos desde un bloque de memoria no administrado a un objeto administrado y recién asignado del tipo especificado por un parámetro de tipo genérico.

PtrToStructure<T>(IntPtr, T)

Calcula las referencias desde un bloque de memoria no administrado a un objeto administrado de un tipo especificado.

PtrToStructure(IntPtr, Object)

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

Precaución

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

Calcula las referencias a los datos desde un bloque de memoria no administrada a un objeto administrado.

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)

Parámetros

ptr
IntPtr

nativeint

Puntero a un bloque de memoria no administrado.

structure
Object

Objeto en el que se copiarán los datos. Este objeto debe ser una instancia de una clase con formato.

Atributos

Excepciones

El diseño de la estructura no es secuencial ni explícito.

o bien

La estructura es un tipo de valor al que se ha aplicado la conversión boxing.

Comentarios

PtrToStructure a menudo es necesario en la interoperabilidad COM e invocación de plataforma cuando los parámetros de estructura se representan como un System.IntPtr valor. No se puede usar este método de sobrecarga con tipos de valor. Si el ptr parámetro es igual IntPtr.Zeroa , null se devolverá.

Se aplica a

PtrToStructure(IntPtr, Type)

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

Precaución

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

Calcula las referencias a los datos desde un bloque de memoria no administrado a un objeto administrado y recién asignado del tipo especificado.

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

Parámetros

ptr
IntPtr

nativeint

Puntero a un bloque de memoria no administrado.

structureType
Type

Tipo de objeto que se va a crear. Este objeto debe representar una clase con formato o una estructura.

Devoluciones

Objeto administrado que contiene los datos a los que apunta el parámetro ptr.

Atributos

Excepciones

El diseño del parámetro structureType no es secuencial ni explícito.

o bien

El parámetro structureType es una definición de tipo genérico.

structureType es null.

La clase que ha especificado el elemento structureType no tiene ningún constructor sin parámetros accesible.

Ejemplos

En el ejemplo siguiente se crea una estructura administrada, se transfiere a la memoria no administrada y, a continuación, se transfiere a la memoria administrada mediante el PtrToStructure método .

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

En el ejemplo siguiente se muestra cómo serializar un bloque de memoria no administrado en una estructura administrada mediante el PtrToStructure método .

Importante

Este código supone la compilación de 32 bits. Antes de usar un compilador de 64 bits, reemplace por IntPtr.ToInt32IntPtr.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);
        }

Comentarios

PtrToStructure a menudo es necesario en la interoperabilidad COM e invocación de plataforma cuando los parámetros de estructura se representan como un System.IntPtr valor. Puede pasar un tipo de valor a este método de sobrecarga. En este caso, el objeto devuelto es una instancia boxed. Si el ptr parámetro es igual IntPtr.Zeroa , null se devolverá.

Consulte también

Se aplica a

PtrToStructure<T>(IntPtr)

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

Serializa las referencias a los datos desde un bloque de memoria no administrado a un objeto administrado y recién asignado del tipo especificado por un parámetro de tipo genérico.

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

Parámetros de tipo

T

Tipo de objeto en el que se copiarán los datos. Este objeto debe ser una clase con formato o una estructura.

Parámetros

ptr
IntPtr

nativeint

Puntero a un bloque de memoria no administrado.

Devoluciones

T

Objeto administrado que contiene los datos a los que apunta el parámetro ptr.

Atributos

Excepciones

El diseño de T no es secuencial ni explícito.

La clase que ha especificado el elemento T no tiene ningún constructor sin parámetros accesible.

Comentarios

PtrToStructure<T>(IntPtr) a menudo es necesario en la interoperabilidad COM e invocación de plataforma cuando los parámetros de estructura se representan como System.IntPtr valores. Puede pasar un tipo de valor a esta sobrecarga de método. Si el ptr parámetro es igual IntPtr.Zero a y T es un tipo de referencia, null se devuelve . Si ptr es IntPtr.Zero igual a y T es un tipo de valor, se produce una NullReferenceException excepción .

Se aplica a

PtrToStructure<T>(IntPtr, T)

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

Calcula las referencias desde un bloque de memoria no administrado a un objeto administrado de un tipo especificado.

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)

Parámetros de tipo

T

Tipo de structure. Debe ser una clase con formato.

Parámetros

ptr
IntPtr

nativeint

Puntero a un bloque de memoria no administrado.

structure
T

Objeto en el que se copiarán los datos.

Atributos

Excepciones

El diseño de la estructura no es secuencial ni explícito.

Comentarios

PtrToStructure<T>(IntPtr, T) a menudo es necesario en la interoperabilidad COM e invocación de plataforma cuando los parámetros de estructura se representan como IntPtr valores. No se puede usar esta sobrecarga de método con tipos de valor. Si el ptr parámetro es igual IntPtr.Zero a y T es un tipo de referencia, null se devuelve . Si ptr es IntPtr.Zero igual a y T es un tipo de valor, se produce una NullReferenceException excepción .

Se aplica a