Skip to content
Tutorials Center
My learning

Topics

Lesson 163 of 182 ยท Advanced C#

Interop, COM and Native Code

Call native C libraries from C#: P/Invoke, marshalling strings and structs, callbacks, function pointers, NativeLibrary, LibraryImport, error codes and the COM basics.

C# does not live alone. Operating systems expose their features as C functions (files, windows, sockets, sensors). Great libraries exist in C and C++ and will never be rewritten (image codecs, compression, databases, machine-learning runtimes). Older Windows software exposes objects through COM. Interop is the set of tools that lets managed .NET code call all of that, and lets native code call back into .NET.

The tool you will use most is P/Invoke (Platform Invoke): you declare a C function in C# with an attribute, and the runtime finds the function in a shared library and calls it for you. The hard part is not the call itself; it is the data. A C char*, a C struct and a managed string or object are different things, and marshalling is the process of converting between them. This lesson builds up from a one-line call to callbacks and function pointers.

If you want the lower-level view of pointers and fixed, read unsafe code and interop first, and the next lesson, pointers, stackalloc and low-level memory, goes further into memory itself.

Our in-browser editor runs your code on a Linux server, so the runnable examples call functions from the C library (libc) that every Linux system has. On Windows you would call kernel32.dll or user32.dll; on macOS libSystem. The ideas are identical; only the library and function names change. You can test any of this code at home with the .NET SDK.

Your first P/Invoke

A P/Invoke declaration is a static extern method with no body, marked [DllImport]. The attribute names the library; the method signature must match the C function.

The C library has int abs(int) and size_t strlen(const char*). We call both:

C# Calling abs and strlen from libc

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.

Look at the result: the string has 5 characters, but strlen reports 6, because รฉ takes two bytes in UTF-8 and strlen counts bytes up to the terminating zero. The attribute [MarshalAs(UnmanagedType.LPUTF8Str)] told the runtime to convert the .NET string (UTF-16) into a temporary null-terminated UTF-8 buffer, pass a pointer to it, and free it after the call.

Some points to remember:

  • Names: "libc" is resolved by the runtime, which tries variations (libc.so, libc, and so on). Libraries are loaded the first time you call into them, not at program start.
  • Types: C int is 32 bits, so int. C size_t and long on 64-bit Linux are pointer-sized: use nuint and nint. C long is 32-bit on Windows but 64-bit on Linux and macOS, a classic portability trap. Use CLong/CULong when the C header says long.
  • Strings: always say how text is encoded. Without MarshalAs, a default applies that differs by platform and CharSet, and on non-Windows platforms it is UTF-8 for ANSI. Prefer being explicit.

When the call cannot be made

A P/Invoke can fail before your code runs. The two common errors are a missing library and a missing function. Both are exceptions you can catch, and both appear at the first call, not when the program starts.

C# Missing libraries and missing functions

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.

NativeLibrary (in System.Runtime.InteropServices) is the API for loading libraries yourself: Load, TryLoad, GetExport and Free. It is useful for optional dependencies ("use the fast native library if it is installed, otherwise a managed fallback").

Error codes: SetLastError

Many C functions report failure by returning -1 or null and putting a reason in a thread-local variable (errno on Linux, GetLastError on Windows). That variable can be overwritten by anything the runtime does between your call and your read, so you must not read it yourself. Instead set SetLastError = true; the runtime then captures the value immediately after the native call, and you read it with Marshal.GetLastPInvokeError().

C# Reading errno safely

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.

Error 2 is "No such file or directory" (ENOENT) on Linux. On Windows you would pass the Win32 error code to new Win32Exception(code) to get its message.

Structs: layout and marshalling

A C struct is a block of bytes with fixed field offsets. A C# struct can be laid out the same way if you tell the runtime so with [StructLayout]. A type that has the same representation in managed and native memory is blittable: numbers, pointers, and structs made only of those. A blittable struct is passed by copying its bytes, which is fast. Types such as string, bool and arrays are not blittable and need conversion.

The C function div_t div(int numerator, int denominator) returns a struct by value containing quotient and remainder:

C# A struct returned by value

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 field order must match the C declaration, and the sizes and alignment must match too. C compilers insert padding so each field starts at a multiple of its size. You can inspect what the runtime computes.

C# Sizes, padding and Pack

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 matches C code compiled with #pragma pack(1), typical for binary file formats and network headers. LayoutKind.Explicit with FieldOffset models unions.

If your struct does not match the native layout exactly, nothing fails loudly. You just read garbage or corrupt memory. Check the C header, check sizeof on the C side, and check Marshal.SizeOf on the C# side.

Callbacks: native code calling you

Some C functions take a function pointer, for example qsort, which sorts any array and asks you how to compare two elements. In C# there are two ways to pass one.

A delegate. The runtime builds a native-callable thunk for it. This is the easy way, but you must keep the delegate alive for as long as native code may call it. If the garbage collector collects it, the native side holds a pointer to freed memory and the process crashes. GC.KeepAlive or a field that holds the delegate prevents this.

A function pointer to an [UnmanagedCallersOnly] static method. This is faster and works with Native AOT, and there is no delegate to keep alive.

C# qsort with a delegate callback

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 exact number and order of comparisons is up to the C library's sort algorithm, so the program prints only whether the callback ran. Now the function-pointer version, which needs unsafe (our editor allows it):

C# qsort with an UnmanagedCallersOnly function 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.

fixed pins the managed array so the garbage collector cannot move it while native code uses its address, and &Compare takes the address of the callback with no delegate allocation. A callback method must not let an exception escape into native code: an unhandled exception there crashes the process, so catch everything inside.

Choosing the library at run time

Hard-coding a library name breaks when the name differs per platform (kernel32.dll, libc.so.6, libSystem.dylib). The runtime lets you intercept the lookup with NativeLibrary.SetDllImportResolver. Here a made-up name is mapped to the C library:

C# A custom DllImport resolver

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 also load a function pointer directly with NativeLibrary.GetExport(handle, "name") and cast it to a delegate* unmanaged<...>.

LibraryImport: the modern P/Invoke

[DllImport] marshals at run time, using IL that the runtime generates on first call. That requires the JIT and hides costs. Since .NET 7 there is a source-generated replacement, [LibraryImport], which writes the marshalling code at compile time using the source generator machinery. It is faster to start, allocation-conscious, and works with Native AOT. The declaration is partial:

C#
// Read-only: needs a project build with the .NET 7+ SDK, because a generator supplies the body.
using System.Runtime.InteropServices;

public static partial class Native
{
    [LibraryImport("libc", StringMarshalling = StringMarshalling.Utf8)]
    public static partial nuint strlen(string text);

    [LibraryImport("libc", SetLastError = true, StringMarshalling = StringMarshalling.Utf8)]
    public static partial int chdir(string path);
}

The SDK ships an analyzer (SYSLIB1054) that offers to convert existing DllImport declarations. In new code, use LibraryImport and keep DllImport only where it is not supported.

Handles: do not leak native resources

Native APIs often return a handle: a file, a window, a database connection. Store it in a SafeHandle subclass (SafeFileHandle for files is built in) rather than a bare IntPtr. A safe handle releases the resource even if an exception interrupts, integrates with using and IDisposable, and keeps the handle alive during a call. This sketch uses Windows names, so it is read-only:

C#
// Read-only: Windows only.
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;

sealed class MyHandle : SafeHandleZeroOrMinusOneIsInvalid
{
    public MyHandle() : base(ownsHandle: true) { }

    protected override bool ReleaseHandle() => CloseHandle(handle);

    [DllImport("kernel32.dll")]
    private static extern bool CloseHandle(IntPtr h);
}

Calling your own C library

To try this with code you control, write a tiny C file, compile it to a shared library and call it. These commands run on your machine, not in the editor:

Terminal
# Read-only: on Linux (use .dll on Windows, .dylib on macOS)
cat > adder.c <<'EOF'
int add(int a, int b) { return a + b; }
EOF
gcc -shared -fPIC -o libadder.so adder.c
C#
// Read-only: in a project next to libadder.so (copy it to the output folder).
using System.Runtime.InteropServices;

Console.WriteLine(Native.add(2, 3));    // 5

static class Native
{
    [DllImport("adder")]                 // finds libadder.so by convention
    public static extern int add(int a, int b);
}

For C++ libraries, expose a plain C interface with extern "C", because C++ names are mangled by the compiler and classes cannot be called directly.

COM in a nutshell

COM (Component Object Model) is Windows' older binary standard for objects: Office automation, DirectX, shell extensions and many legacy business components are COM. A COM object is accessed through interfaces whose first three methods are always QueryInterface, AddRef and Release (the IUnknown contract), with reference counting instead of garbage collection.

.NET hides most of this. A COM object appears as a managed object (a runtime callable wrapper) that releases the native reference when collected. You declare the interface with [ComImport] and [Guid], or since .NET 8 with the source-generated [GeneratedComInterface]. Threads matter: many COM components require a single-threaded apartment (STA). COM is Windows-only, so everything here is read-only, and it is usually used through libraries or generated wrappers rather than written by hand.

C#
// Read-only: Windows only, requires Excel installed.
Type excelType = Type.GetTypeFromProgID("Excel.Application")!;
dynamic excel = Activator.CreateInstance(excelType)!;
excel.Visible = true;
excel.Quit();

Practical advice

  • Prefer a managed library when one exists. Interop adds failure modes: missing files, wrong CPU architecture (a 64-bit process cannot load a 32-bit DLL), and platform differences.
  • Write the thinnest possible declaration layer, and wrap it in a normal C# class with validation and exceptions. Keep IntPtr out of your public API.
  • You own every allocation made on the native side. Pair AllocHGlobal with FreeHGlobal, and use SafeHandle or IDisposable so the pairing survives exceptions.
  • Test on every target platform and CPU. Sizes of long, wchar_t and structs differ.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does [DllImport] do?

    A DllImport method has no body. The runtime locates the named native function and calls it, marshalling arguments and the return value.
  2. 2. Why does strlen("hรฉllo") return 6 in the lesson's example?

    LPUTF8Str converts the string to UTF-8 bytes. h, l, l, o take one byte each and e-acute takes two, so strlen counts 6 bytes (the terminator is not counted).
  3. 3. Why set SetLastError = true on a P/Invoke instead of reading errno yourself afterwards?

    The thread's error value can be changed by the runtime between your call and your read. SetLastError saves it right after the native call and Marshal.GetLastPInvokeError returns that saved value.
  4. 4. What must you do when you pass a delegate as a callback to native code?

    The native side only holds a raw pointer. If the delegate is collected, the pointer dangles and a later callback crashes the process.
  5. 5. What is the main advantage of LibraryImport over DllImport?

    LibraryImport is a source generator that emits the marshalling stub during the build, so no IL stub generation is needed at run time.

Summary

  • P/Invoke declares native functions in C# ([DllImport] or, in new code, source-generated [LibraryImport]).
  • Marshalling converts managed data to native data: choose the string encoding explicitly, match integer sizes (nint, nuint, CLong) and verify struct layout with Marshal.SizeOf and OffsetOf.
  • Use SetLastError = true and Marshal.GetLastPInvokeError() for native error codes.
  • Callbacks are passed as delegates (keep them alive) or [UnmanagedCallersOnly] function pointers; never let exceptions escape into native code.
  • Use NativeLibrary and DllImportResolver to pick libraries at run time, and SafeHandle to own native handles.
  • COM is a Windows object model accessed through wrappers; most code uses generated wrappers or libraries.

Next: Pointers, stackalloc and Low-level Memory