Marshals data from an unmanaged block of memory to a newly allocated managed object of the specified type.
<ComVisibleAttribute(True)> _ <SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags := SecurityPermissionFlag.UnmanagedCode)> _ Public Shared Function PtrToStructure ( _ ptr As IntPtr, _ structureType As Type _ ) As Object
Dim ptr As IntPtr Dim structureType As Type Dim returnValue As Object returnValue = Marshal.PtrToStructure(ptr, _ structureType)
[ComVisibleAttribute(true)] [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] public static Object PtrToStructure( IntPtr ptr, Type structureType )
[ComVisibleAttribute(true)] [SecurityPermissionAttribute(SecurityAction::LinkDemand, Flags = SecurityPermissionFlag::UnmanagedCode)] public: static Object^ PtrToStructure( IntPtr ptr, Type^ structureType )
public static function PtrToStructure( ptr : IntPtr, structureType : Type ) : Object
The structureType parameter layout is not sequential or explicit.
-or-
The structureType parameter is a generic type.
structureType is nullNothingnullptra null reference (Nothing in Visual Basic).
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.
This method uses SecurityAction..::.LinkDemand to prevent it from being called from untrusted code; only the immediate caller is required to have SecurityPermissionAttribute..::.UnmanagedCode permission. If your code can be called from partially trusted code, do not pass user input to Marshal class methods without validation. For important limitations on using the LinkDemand member, see Demand vs. LinkDemand.
The following code example creates a managed structure, transfers it to unmanaged memory, and then transfers it back to managed memory using the PtrToStructure method.
Imports System 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
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 code example demonstrates how to marshal an unmanaged block of memory to a managed structure using the PtrToStructure method.
[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); }
[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); }
for permission to call unmanaged code.
Associated enumeration: UnmanagedCode Security action: LinkDemand
Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune