Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Reflection, Attributes and Metadata

Marshalling and the Marshal class

Reference for C# marshalling: convert data between managed and native memory with the Marshal class, StructLayout, MarshalAs, callbacks and SafeHandle.

Marshalling is the conversion of data between managed objects and the raw memory layout a native library expects. Some types are blittable: int, double, pointers and structs made only of them have the same bit pattern on both sides and are passed directly. Others (string, bool, arrays of non-blittable types, classes) must be converted, and you control how with attributes such as [MarshalAs] and [StructLayout] and with the helper class System.Runtime.InteropServices.Marshal.

You use marshalling together with P/Invoke, when hosting COM objects, or when you work with unmanaged buffers yourself.

C#
[StructLayout(LayoutKind.Sequential)]
struct Pair { public int A; public int B; }

int size = Marshal.SizeOf<Pair>();       // 8

Try it

C# Structs, pointers and unmanaged memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Struct by value and a callback delegate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
[StructLayout(LayoutKind.Sequential | Explicit | Auto, Pack = n, CharSet = ...)]
[FieldOffset(n)]                         // with LayoutKind.Explicit
[MarshalAs(UnmanagedType.LPUTF8Str)]     // per field or parameter
[In] [Out]                               // direction for arrays and structs
API Description
Marshal.SizeOf<T>() Unmanaged size of a type, including padding.
Marshal.AllocHGlobal / FreeHGlobal Unmanaged heap block. Always free it.
Marshal.StructureToPtr / PtrToStructure Copy a struct to or from unmanaged memory.
Marshal.ReadInt32, WriteInt32, Copy Raw reads and writes.
Marshal.StringToCoTaskMemUTF8, PtrToStringUTF8 Strings as UTF-8 buffers.
Marshal.GetFunctionPointerForDelegate Get a native function pointer for a managed delegate.
UnmanagedType The target representation: Bool (4 bytes), U1, LPStr, LPWStr, LPUTF8Str, ByValArray, FunctionPtr and more.

Errors: ArgumentException when a type cannot be marshalled (for example a struct containing a managed reference without MarshalAs); native memory errors (wrong sizes, freed pointers) are not exceptions but crashes.

Usage notes

  • Sequential layout is the default for structs, and the one to use for native interop. Classes default to Auto, which the runtime may reorder: do not pass them to native code without explicit layout.
  • bool is 4 bytes in P/Invoke by default (Win32 BOOL). Use [MarshalAs(UnmanagedType.U1)] for a C bool.
  • Keep delegates alive. If the garbage collector collects a delegate while native code still holds its function pointer, the next callback crashes. Store it in a field or GC.KeepAlive it.
  • Pinned arrays: the marshaller pins blittable arrays during the call; for longer lifetimes use GCHandle or fixed.
  • Free what you allocate, and with the matching function (AllocHGlobal/FreeHGlobal, AllocCoTaskMem/FreeCoTaskMem). Prefer SafeHandle subclasses so release happens even on exceptions.
  • Span-based APIs: MemoryMarshal, Span<byte> and stackalloc avoid copies for many tasks that once needed Marshal.
  • Generated marshalling: [LibraryImport] and [GeneratedComInterface] produce this code at compile time, which is AOT-friendly.