Skip to content
Tutorials Center
My learning

Topics

Lesson 112 of 182 ยท Memory and Performance

Unsafe Code and Interop

Learn when and how to use unsafe code in C#: pointers, fixed, stackalloc, NativeMemory, Marshal and P/Invoke for calling native libraries, plus NativeAOT limits and safer options.

Almost everything in C# is safe code: the runtime checks array bounds, tracks object lifetimes, and stops you from reading memory that is not yours. That safety is why you rarely see crashes from memory corruption. But sometimes you need to step outside it: to call a function from a native library written in C, to talk to hardware or an operating-system API, to process a huge buffer with the fewest possible checks, or to read a binary file format by overlaying a struct onto raw bytes.

C# has an escape hatch for these cases: the unsafe keyword, which enables pointers like in C, along with fixed, stackalloc, the NativeMemory class and the Marshal and P/Invoke machinery for crossing into native code. This lesson explains each tool, shows runnable examples, and, just as importantly, tells you when not to use them, because modern C# offers spans and other safe tools that cover most needs.

Unsafe code can corrupt memory, crash the process and open security holes. Bugs in it do not throw tidy exceptions; they may appear far away from their cause. Use it only when you have a measured need or when you must call native code, and keep the unsafe part small and well tested.

Enabling unsafe code

The compiler rejects the unsafe keyword unless you opt in. In a real project you add one line to the project file:

XML
<!-- MyApp.csproj (read-only): allow unsafe blocks in this project -->
<PropertyGroup>
  <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>

The editor on this site already compiles with unsafe code allowed, so the examples below run. You mark code with unsafe on a method, a type or a block.

Pointers in a nutshell

A pointer holds a memory address. int* is "pointer to int". Three operators matter:

  • &x takes the address of a variable.
  • *p reads or writes the value at the address (dereference).
  • p->Field accesses a field of the struct a pointer points to.

Pointer arithmetic is in units of the element type: p + 1 moves by sizeof(int) bytes for an int*.

C# Pointers, addresses and arithmetic

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.

Here stackalloc returns a raw int*. (Assigning it to a Span<int> is the safe form, so prefer that.) Never print or compare raw addresses in tests; they change on every run.

fixed: pinning managed objects

The garbage collector can move objects during a compaction. A pointer into an array would suddenly point at the wrong place. The fixed statement pins the object for the duration of the block, so you can safely hold a pointer into it.

C# fixed: a pointer into a managed array

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.

Pinning has a cost: while pinned, the GC cannot move the object, which can fragment the heap. Keep fixed blocks short. An empty array gives a null pointer, so check the length first.

Structs and layout

Pointers to structs let you view raw bytes as structured data. StructLayout controls how fields are placed (see also boxing and structs for size and padding).

C# Reading a binary header through a struct pointer

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.

Pack = 1 removes padding so the struct matches the file layout exactly. Remember the byte order: x86 and ARM are little-endian, but many file and network formats are big-endian, and then you must convert (for example with BinaryPrimitives.ReverseEndianness). A safe alternative is MemoryMarshal.Read<Header>(file) or BinaryPrimitives.ReadUInt32LittleEndian(span), which need no unsafe at all.

Unmanaged memory: NativeMemory and Marshal

Memory you allocate yourself, outside the GC heap, is unmanaged: the GC neither moves nor frees it. You must free it, exactly once. The modern API is NativeMemory (.NET 6):

C# Allocating and freeing 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.

Notice the Span<int> over the pointer: you can do the risky allocation in a tiny unsafe region and hand the rest of the program a bounds-checked span.

The older Marshal class (System.Runtime.InteropServices.Marshal) provides AllocHGlobal, StructureToPtr and string conversion helpers. It is still the usual way to move data between managed and native shapes:

C# Marshal: structs and strings to 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.

The rule is the same everywhere: whoever allocates must free with the matching function. Mixing AllocHGlobal with FreeCoTaskMem or NativeMemory.Free is a bug.

For a managed wrapper that cannot leak, use SafeHandle (see IDisposable), which ties native handle release to Dispose and a finalizer.

Calling native code: P/Invoke

Platform Invoke (P/Invoke) lets C# call functions exported by native libraries (DLLs on Windows, .so on Linux, .dylib on macOS) through the DllImport attribute or, in modern code, the source-generated LibraryImport. Our sandbox cannot call arbitrary native libraries, so these examples are read-only. They show what you would write on your machine in a normal project (the LibraryImport source generator comes with the SDK build, which our single-file editor does not run).

A classic call to the Windows API:

C#
// Read-only: Windows only. Not runnable in the site editor.
using System.Runtime.InteropServices;

static partial class NativeMethods
{
    [LibraryImport("user32.dll", EntryPoint = "MessageBoxW", StringMarshalling = StringMarshalling.Utf16)]
    internal static partial int MessageBox(IntPtr hWnd, string text, string caption, uint type);
}

// NativeMethods.MessageBox(IntPtr.Zero, "Hello from C#", "Demo", 0);

And the same idea on Linux or macOS, calling the C library:

C#
// Read-only: Linux and macOS. Not runnable in the site editor.
using System.Runtime.InteropServices;

static partial class Libc
{
    [LibraryImport("libc", EntryPoint = "getpid")]
    internal static partial int GetProcessId();

    [LibraryImport("libc", EntryPoint = "strlen")]
    internal static partial nuint StringLength(
        [MarshalAs(UnmanagedType.LPUTF8Str)] string text);
}

// Console.WriteLine(Libc.StringLength("hello"));   // 5

Things to get right with P/Invoke:

  • Match the native signature exactly. Wrong parameter types or calling conventions give garbage values or crashes.
  • Know the data sizes. C long is 32 bits on Windows and 64 on Linux; use nint, nuint and fixed-size types such as int and long deliberately.
  • Choose a string encoding (StringMarshalling.Utf8 or Utf16) to match the native side.
  • Check the return value or GetLastError (SetLastError = true) and turn failures into exceptions.
  • Prefer LibraryImport over DllImport: it generates the marshalling code at compile time, which is faster and works with NativeAOT.
  • Callbacks from native code use function pointers (delegate* unmanaged) or delegates kept alive by your code, or the GC may free them while native code still calls them.
  • Often a managed API exists. Before writing P/Invoke for files, processes, environment, or sockets, check the standard library first. A wrapper NuGet package may already exist for the library you need.

Function pointers

C# 9 added function pointers (delegate*), which call a method through its address without allocating a delegate. They are faster but unsafe, and mainly useful for interop and very hot paths.

C# A function pointer to a static method

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.

You can only take the address of a static method, and the pointer carries no instance or closure. For ordinary callbacks, delegates and lambdas are the right tool.

NativeAOT and trimming

Ahead-of-time compilation with NativeAOT (PublishAot) compiles your app into a native executable with no JIT. It starts fast and needs no installed runtime, but there are limits that matter for interop:

  • No runtime code generation, so built-in runtime marshalling for P/Invoke with complex types is restricted. LibraryImport source generators are the supported path.
  • Reflection that the trimmer cannot see statically may break.
  • You cannot load managed assemblies dynamically.
Terminal
# Read-only: what you would run on your machine
dotnet publish -c Release -r linux-x64 -p:PublishAot=true

Safer alternatives first

Before reaching for unsafe, check whether one of these covers your need:

Need Safe tool
Slice or parse memory without copying Span<T>, ReadOnlySpan<T> (spans)
Reinterpret bytes as structs MemoryMarshal.Cast, MemoryMarshal.Read, BinaryPrimitives
Temporary buffer stackalloc into a Span<T>, ArrayPool<T> (fast lookups)
Avoid bounds checks Loop patterns the JIT can prove safe (for (int i = 0; i < span.Length; i++)), foreach
Wrap a native handle SafeHandle
Vectorized math System.Numerics.Vector<T>, System.Runtime.Intrinsics
Native function call LibraryImport / DllImport

The usual path to speed is not pointers but fewer allocations and better algorithms (see measuring performance). In .NET, many "unsafe tricks" from the past are now done as well or better by Span<T>, and the JIT removes bounds checks in simple loops.

When you really need unsafe

  • Interop with C libraries, drivers and OS APIs that use pointers, buffers or callbacks.
  • Implementing low-level building blocks (a custom memory allocator, a serializer, a parser) after benchmarks show that safe code is too slow.
  • Reading binary formats in place.

When you do, follow these habits: keep unsafe code in a small, well-named class; validate sizes and indexes before the first dereference; always pair every allocation with a free in finally; test with large and empty inputs; and document ownership ("the caller frees", "the callee copies").

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the fixed statement exist?

    The GC can relocate managed objects. fixed pins the object for the duration of the block so the pointer stays valid.
  2. 2. If p is an int*, what does p + 1 point to?

    Pointer arithmetic is scaled by the element size, so adding 1 to an int* advances by 4 bytes.
  3. 3. You allocated memory with NativeMemory.Alloc. What must you do?

    Unmanaged memory is outside the GC heap. You own it and must free it with the matching function, normally in a finally block.
  4. 4. Which is the preferred modern way to declare a P/Invoke?

    LibraryImport uses a source generator, giving faster startup, fewer surprises and compatibility with NativeAOT.
  5. 5. What is the best first step when you think you need pointers for speed?

    Most performance problems are solved with safe tools. Unsafe code is a last resort after measurements show it is needed.

Summary

  • unsafe code allows pointers (*, &, ->) and needs the AllowUnsafeBlocks project setting. It removes the runtime's safety checks, so bugs can corrupt memory.
  • Pointer arithmetic is scaled by element size. fixed pins managed objects while you use a pointer into them.
  • stackalloc, NativeMemory and Marshal give you stack and unmanaged memory; you must free unmanaged memory exactly once. Wrap it in a Span<T> or SafeHandle to keep the unsafe part small.
  • P/Invoke (LibraryImport, DllImport) calls native libraries; match signatures, sizes, encodings and error handling carefully. Those calls cannot run in our editor.
  • Function pointers (delegate*) call static methods without delegates; NativeAOT restricts runtime-generated marshalling and reflection.
  • Prefer safe tools first (spans, MemoryMarshal, BinaryPrimitives, SafeHandle), and use unsafe code only for interop or measured hot spots.

Next: Dates and Times