System.Runtime.InteropServices.Marshal.StructureToPtr Method

Marshals data from a managed object to an unmanaged block of memory.

Syntax

[System.Runtime.ConstrainedExecution.ReliabilityContract(System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState, System.Runtime.ConstrainedExecution.Cer.MayFail)]
[System.Runtime.InteropServices.ComVisible(true)]
public static void StructureToPtr (object structure, IntPtr ptr, bool fDeleteOld)

Parameters

structure
A managed object that holds the data to be marshaled. This object must be a structure or an instance of a formatted class.
ptr
A pointer to an unmanaged block of memory, which must be allocated before this method is called.
fDeleteOld
true to call the Marshal.DestroyStructure(IntPtr, Type) method on the ptr parameter before this method copies the data. The block must contain valid data. Note that passing false when the memory block already contains data can lead to a memory leak.

Remarks

If structure is a value type, it can be boxed or unboxed. If it is boxed, it is unboxed before copying.

A formatted class is a reference type whose layout is specified by the System.Runtime.InteropServices.StructLayoutAttribute attribute, as either LayoutKind.Explicit or LayoutKind.Sequential.

Marshal.StructureToPtr(object, IntPtr, bool) copies the contents of structure to the pre-allocated block of memory that the ptr parameter points to. If structure contains reference types that marshal to COM interface pointers (interfaces, classes without layout, and object), the managed objects are kept alive with reference counts. All other reference types (for example, strings and arrays) are marshaled to copies. To release these managed or unmanaged objects, you must call the Marshal.DestroyStructure(IntPtr, Type) method before you free the memory block.

If you use the Marshal.StructureToPtr(object, IntPtr, bool) method to copy a different instance to the memory block at a later time, specify true for fDeleteOld to remove reference counts for reference types in the previous instance. Otherwise, the managed reference types and unmanaged copies are effectively leaked.

The overall pattern for using Marshal.StructureToPtr(object, IntPtr, bool) is as follows:

[The 'ordered' type of list has not been implemented in the ECMA stylesheet.]
Note:

To pin an existing structure instead of copying it, use the System.Runtime.InteropServices.GCHandle type to create a pinned handle for the structure. For details on how to pin, see Copying and Pinning.

Requirements

Namespace: System.Runtime.InteropServices
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0