블로그 이미지
Every unexpected event is a path to learning for you.

카테고리

분류 전체보기 (2731)
Unity3D (814)
Programming (474)
Server (33)
Unreal (4)
Gamebryo (56)
Tip & Tech (228)
협업 (57)
3DS Max (3)
Game (12)
Utility (136)
Etc (96)
Link (32)
Portfolio (19)
Subject (90)
iOS,OSX (51)
Android (14)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (3)
Memories (20)
Interest (38)
Thinking (38)
한글 (30)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (18)
Exercise (3)
나만의 맛집 (3)
냥이 (10)
육아 (16)
Total
Today
Yesterday
03-28 00:02

C#에서 포인터

Programming/C# / 2011. 11. 15. 14:18

Marshal.PtrToStructure 메서드 (IntPtr, Type)

.NET Framework 4

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

네임스페이스:  System.Runtime.InteropServices
어셈블리:  mscorlib(mscorlib.dll)
[ComVisibleAttribute(true)]
public static Object PtrToStructure(
	IntPtr ptr,
	Type structureType
)

매개 변수

ptr
형식: System.IntPtr
관리되지 않는 메모리 블록에 대한 포인터입니다.
structureType
형식: System.Type
만들 개체의 형식입니다. 이 개체는 서식이 지정된 클래스나 구조체를 나타내야 합니다. 

반환 값

형식: System.Object
ptr 매개 변수가 가리키는 데이터가 있는 관리되는 개체입니다.
예외상황
ArgumentException

structureType 매개 변수 레이아웃이 Sequential 또는 Explicit이 아닌 경우

또는

structureType 매개 변수가 제네릭 형식인 경우

ArgumentNullException

structureType는 Nothing입니다.

PtrToStructure는 주로 구조체 매개 변수를 System.IntPtr 값으로 나타낼 때 COM interop 및 플랫폼 호출에 필요합니다. 값 형식을 이 오버로드 메서드에 전달할 수 있습니다. 이 경우 반환된 개체는 boxing된 인스턴스입니다.

다음 예제에서는 관리되는 구조체를 만들고 이를 관리되지 않는 메모리로 전달한 다음 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);
        }



    }

}


다음 예제에서는 PtrToStructure 메서드를 사용하여 관리되지 않는 메모리 블록을 관리되는 구조체로 마샬링하는 방법을 보여 줍니다.

		[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);

		}


.NET Framework

4, 3.5, 3.0, 2.0, 1.1, 1.0에서 지원

.NET Framework Client Profile

4, 3.5 SP1에서 지원
  • SecurityCriticalAttribute  

    직접 실행 호출자에 대한 완전 신뢰가 필요합니다. 이 멤버는 부분적으로 신뢰할 수 있거나 투명한 코드에서 사용할 수 없습니다.

Windows 7, Windows Vista SP1 이상, Windows XP SP3, Windows XP SP2 x64 버전, Windows Server 2008(Server Core는 지원되지 않음), Windows Server 2008 R2(Server Core는 SP1 이상에서 지원됨), Windows Server 2003 SP2

.NET Framework에서 모든 플랫폼의 전체 버전을 지원하지는 않습니다. 지원되는 버전의 목록을 보려면 .NET Framework 시스템 요구 사항을 참조하십시오.



반응형
Posted by blueasa
, |