Marshal.PtrToStructure Метод

Определение

Маршалирует данные из неуправляемого блока памяти в управляемый объект.

Перегрузки

PtrToStructure(IntPtr, Object)
Устаревшие..

Маршалирует данные из неуправляемого блока памяти в управляемый объект.

PtrToStructure(IntPtr, Type)
Устаревшие..

Маршалирует данные из неуправляемого блока памяти во вновь выделенный управляемый объект указанного типа.

PtrToStructure<T>(IntPtr)

Маршалирует данные из неуправляемого блока памяти во вновь выделенный управляемый объект типа, указанного параметром универсального типа.

PtrToStructure<T>(IntPtr, T)

Выполняет маршалирование данных из неуправляемого блока памяти в управляемый объекта указанного типа.

PtrToStructure(IntPtr, Object)

Исходный код:
Marshal.cs
Исходный код:
Marshal.cs
Исходный код:
Marshal.cs

Внимание!

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

Маршалирует данные из неуправляемого блока памяти в управляемый объект.

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)

Параметры

ptr
IntPtr

nativeint

Указатель на неуправляемый блок памяти.

structure
Object

Объект, в который копируются данные. Он должен представлять собой экземпляр форматированного класса.

Атрибуты

Исключения

Распределение структуры не является ни последовательным, ни явным.

-или-

Структура принадлежит к упакованному типу значений.

Комментарии

PtrToStructure часто требуется при COM-взаимодействии и вызове платформы, когда параметры структуры представлены в виде System.IntPtr значения. Этот метод перегрузки нельзя использовать с типами значений. ptr Если параметр равен IntPtr.Zero, null возвращается значение .

Применяется к

PtrToStructure(IntPtr, Type)

Исходный код:
Marshal.cs
Исходный код:
Marshal.cs
Исходный код:
Marshal.cs

Внимание!

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

Маршалирует данные из неуправляемого блока памяти во вновь выделенный управляемый объект указанного типа.

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

Параметры

ptr
IntPtr

nativeint

Указатель на неуправляемый блок памяти.

structureType
Type

Тип создаваемого объекта. Этот объект должен представлять форматированный класс или структуру.

Возвращаемое значение

Управляемый объект, содержащий данные, на которые указывает параметр ptr.

Атрибуты

Исключения

Распределения параметра structureTypeне является ни последовательным, ни явным.

-или-

Параметр structureType является определением универсального типа.

structureType имеет значение null.

Класс, указанный в structureType, не имеет доступного конструктора без параметров.

Примеры

В следующем примере создается управляемая структура, она передается в неуправляемую память, а затем передается обратно в управляемую PtrToStructure память с помощью метода .

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

В следующем примере показано, как маршалировать неуправляемый блок памяти в управляемую структуру с помощью PtrToStructure метода .

Важно!

В этом коде предполагается 32-разрядная компиляция. Перед использованием 64-разрядного компилятора замените на 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);
        }

Комментарии

PtrToStructure часто требуется при COM-взаимодействии и вызове платформы, когда параметры структуры представлены в виде System.IntPtr значения. Этот метод перегрузки можно передать тип значения. В этом случае возвращаемый объект является упакованным экземпляром. ptr Если параметр равен IntPtr.Zero, null возвращается значение .

См. также раздел

Применяется к

PtrToStructure<T>(IntPtr)

Исходный код:
Marshal.cs
Исходный код:
Marshal.cs
Исходный код:
Marshal.cs

Маршалирует данные из неуправляемого блока памяти во вновь выделенный управляемый объект типа, указанного параметром универсального типа.

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

Параметры типа

T

Тип объекта, в который копируются данные. Это должен быть форматированный класс или структура.

Параметры

ptr
IntPtr

nativeint

Указатель на неуправляемый блок памяти.

Возвращаемое значение

T

Управляемый объект, содержащий данные, на которые указывает параметр ptr.

Атрибуты

Исключения

Макет T не является ни последовательным, ни явным.

Класс, указанный в T, не имеет доступного конструктора без параметров.

Комментарии

PtrToStructure<T>(IntPtr) часто требуется при COM-взаимодействии и вызове платформы, когда параметры структуры представлены в виде System.IntPtr значений. Вы можете передать тип значения в перегрузку этого метода. ptr Если параметр равен IntPtr.Zero и T является ссылочным типом, null возвращается значение . Если ptr равно IntPtr.Zero и T является типом значения, NullReferenceException возникает исключение .

Применяется к

PtrToStructure<T>(IntPtr, T)

Исходный код:
Marshal.cs
Исходный код:
Marshal.cs
Исходный код:
Marshal.cs

Выполняет маршалирование данных из неуправляемого блока памяти в управляемый объекта указанного типа.

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)

Параметры типа

T

Тип параметра structure. Этот должен быть форматированный класс.

Параметры

ptr
IntPtr

nativeint

Указатель на неуправляемый блок памяти.

structure
T

Объект, в который копируются данные.

Атрибуты

Исключения

Распределение структуры не является ни последовательным, ни явным.

Комментарии

PtrToStructure<T>(IntPtr, T) часто требуется при COM-взаимодействии и вызове платформы, когда параметры структуры представлены в виде IntPtr значений. Эту перегрузку метода нельзя использовать с типами значений. ptr Если параметр равен IntPtr.Zero и T является ссылочным типом, null возвращается значение . Если ptr равно IntPtr.Zero и T является типом значения, NullReferenceException возникает исключение .

Применяется к