Export (0) Print
Expand All

Marshal.PtrToStructure Method (IntPtr, Type)

Marshals data from an unmanaged block of memory to a newly allocated managed object of the specified type.

Namespace:  System.Runtime.InteropServices
Assembly:  mscorlib (in mscorlib.dll)

[ComVisibleAttribute(true)]
public static Object PtrToStructure(
	IntPtr ptr,
	Type structureType
)

Parameters

ptr
Type: System.IntPtr

A pointer to an unmanaged block of memory.

structureType
Type: System.Type

The type of object to be created. This object must represent a formatted class or a structure.

Return Value

Type: System.Object
A managed object containing the data pointed to by the ptr parameter.

ExceptionCondition
ArgumentException

The structureType parameter layout is not sequential or explicit.

-or-

The structureType parameter is a generic type.

ArgumentNullException

structureType is null.

MissingMethodException

The class specified by structureType does not have an accessible default constructor.

PtrToStructure is often necessary in COM interop and platform invoke when structure parameters are represented as an System.IntPtr value. You can pass a value type to this overload method. In this case, the returned object is a boxed instance.

The following example creates a managed structure, transfers it to unmanaged memory, and then transfers it back to managed memory using the PtrToStructure method.

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



    }

}

The following example demonstrates how to marshal an unmanaged block of memory to a managed structure using the PtrToStructure method.

Important noteImportant

This code assumes 32-bit compilation. Before using a 64-bit compiler, replace IntPtr.ToInt32 with IntPtr.ToInt64.

		[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

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0

Portable Class Library

Supported in: Portable Class Library

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8

  • SecurityCriticalAttribute 

    requires full trust for the immediate caller. This member cannot be used by partially trusted or transparent code.

Show:
© 2015 Microsoft