CodeBlanks Logo Icon CodeBlanks

Marshal

C# course · Expert · Lesson 14/47

Learn managed/unmanaged conversion with the Marshal class.

The Marshal class

The System.Runtime.InteropServices.Marshal class performs manual conversion between managed and unmanaged types. For example Marshal.StringToHGlobalAnsi(str) copies a string into native memory; Marshal.FreeHGlobal(ptr) releases it.

This manual marshaling is used for special types that DllImport does not convert automatically. Because you manage memory by hand, calling FreeHGlobal is critical; otherwise a memory leak occurs.

Blittable types

Blittable types have the same memory layout on the managed and unmanaged side; no marshal copy is needed (e.g. int, byte, IntPtr).

Non-blittable types (string, bool, char) require conversion. So when working with native APIs, preferring blittable types improves performance and reduces conversion cost.

Exercise Copy a string with Marshal

In Main copy a string into native memory with IntPtr ptr = Marshal.StringToHGlobalAnsi("Hello");. Print Console.WriteLine("Copied");. Finally release it with Marshal.FreeHGlobal(ptr);.

Show example solution
IntPtr ptr = Marshal.StringToHGlobalAnsi("Hello"); Console.WriteLine("Copied"); Marshal.FreeHGlobal(ptr);
Example solution:
using System;
using System.Runtime.InteropServices;

class Program
{
    static void Main()
    {
        IntPtr ptr = Marshal.StringToHGlobalAnsi("Hello");
        Console.WriteLine("Copied");
        Marshal.FreeHGlobal(ptr);
    }
}

Test yourself

  1. Copy a string into native memory

    IntPtr ptr = Marshal.____("merhaba");
    Show answer
    IntPtr ptr = Marshal.StringToHGlobalAnsi("merhaba");
  2. Which is not a blittable type?

    • int
    • string
    • byte
    • IntPtr
    Show answer

    string — Correct. string is not blittable; it needs marshaling.

  3. Match the Marshal methods

    Marshal.StringToHGlobalAnsi
    String → native memory
    Marshal.FreeHGlobal
    Free native memory
    Marshal.ReadInt32
    Read int from native address
    Marshal.Copy
    Array copy

All lessons in Expert