Marshal.PtrToStructure 메서드

정의

관리되지 않는 메모리 블록의 데이터를 관리되는 개체로 마샬링합니다.

오버로드

PtrToStructure(IntPtr, Object)
사용되지 않음.

관리되지 않는 메모리 블록의 데이터를 관리되는 개체로 마샬링합니다.

PtrToStructure(IntPtr, Type)
사용되지 않음.

관리되지 않는 메모리 블록의 데이터를 지정된 형식의 새로 할당된 관리되는 개체로 마샬링합니다.

PtrToStructure<T>(IntPtr)

관리되지 않는 메모리 블록의 데이터를 제네릭 형식 매개 변수에 의해 지정된 형식의 새로 할당된 관리되는 개체로 마샬링합니다.

PtrToStructure<T>(IntPtr, T)

관리되지 않는 메모리 블록의 데이터를 지정된 형식의 관리되는 개체로 마샬링합니다.

PtrToStructure(IntPtr, Object)

Source:
Marshal.cs
Source:
Marshal.cs
Source:
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

데이터가 복사될 대상 개체입니다. 이 개체는 형식이 지정된 클래스의 인스턴스여야 합니다.

특성

예외

구조체 레이아웃이 Sequential 또는 Explicit이 아닌 경우

또는

구조체가 boxed 값 형식인 경우

설명

PtrToStructure 는 구조체 매개 변수가 값으로 표현될 때 COM interop 및 플랫폼 호출에 System.IntPtr 필요한 경우가 많습니다. 값 형식에는 이 오버로드 메서드를 사용할 수 없습니다. 매개 변수가 ptrIntPtr.Zeronull 같으면 가 반환됩니다.

적용 대상

PtrToStructure(IntPtr, Type)

Source:
Marshal.cs
Source:
Marshal.cs
Source:
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 매개 변수 레이아웃이 Sequential 또는 Explicit이 아닌 경우

또는

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.ToInt64바꿉 IntPtr.ToInt32

[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 interop 및 플랫폼 호출에 System.IntPtr 필요한 경우가 많습니다. 값 형식을 이 오버로드 메서드에 전달할 수 있습니다. 이 경우 반환된 개체는 박스형 instance. 매개 변수가 ptrIntPtr.Zeronull 같으면 가 반환됩니다.

추가 정보

적용 대상

PtrToStructure<T>(IntPtr)

Source:
Marshal.cs
Source:
Marshal.cs
Source:
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 레이아웃이 Sequential 또는 Explicit이 아닌 경우

T에서 지정한 클래스에는 액세스할 수 있는 매개 변수가 없는 생성자가 없습니다.

설명

PtrToStructure<T>(IntPtr) 는 구조 매개 변수가 값으로 System.IntPtr 표현될 때 COM interop 및 platform invoke에서 종종 필요합니다. 값 형식을 이 메서드 오버로드에 전달할 수 있습니다. 매개 변수가 ptrIntPtr.ZeroT 가 참조 형식 null 이면 가 반환됩니다. 가 IntPtr.Zero 같고 T 가 값 형식이면 ptrNullReferenceException throw됩니다.

적용 대상

PtrToStructure<T>(IntPtr, T)

Source:
Marshal.cs
Source:
Marshal.cs
Source:
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

데이터가 복사될 대상 개체입니다.

특성

예외

구조체 레이아웃이 Sequential 또는 Explicit이 아닌 경우

설명

PtrToStructure<T>(IntPtr, T) 는 구조 매개 변수가 값으로 IntPtr 표현될 때 COM interop 및 platform invoke에서 종종 필요합니다. 값 형식에는 이 메서드 오버로드를 사용할 수 없습니다. 매개 변수가 ptrIntPtr.ZeroT 가 참조 형식 null 이면 가 반환됩니다. 가 IntPtr.Zero 같고 T 가 값 형식이면 ptrNullReferenceException throw됩니다.

적용 대상