skip to content

In .NET, what does [LibraryImport] generate at compile time that [DllImport] leaves to the runtime, and what must a project change to switch?

level: seniorimportance: nice to knowfreq 15%

answer

  1. who writes the marshalling code
  2. a stub built at run time
  3. static partial, generated body
  4. unsafe blocks required
  5. CharSet gives way to StringMarshalling

basics

~20 s

[DllImport] has the runtime build and JIT-compile an IL marshalling stub at run time. [LibraryImport] (.NET 7) has a source generator emit that marshalling as C# at build time; methods become static partial and the project needs AllowUnsafeBlocks.

solid answer

~50 s

A `[DllImport]` method is `static extern`: on first call the runtime generates an **IL stub** that marshals parameters and return values and calls the native function, then JIT-compiles that stub. `[LibraryImport]`, added in .NET 7, moves that work into a **Roslyn source generator** shipped with the SDK: you declare the method `static partial` in a `partial` type and the generator writes the implementation, the marshalling plus an inner blittable P/Invoke, as ordinary C# you can read and step through. That removes run-time stub generation, lets the call be inlined, and suits trimming and Native AOT. Switching means: the method becomes `static partial` instead of `static extern`, inside a `partial` type (otherwise error CS0751), `<AllowUnsafeBlocks>true</AllowUnsafeBlocks>` (SYSLIB1062), an explicit `StringMarshalling` such as `Utf8` or `Utf16` because there is no ANSI default (SYSLIB1051), and `[UnmanagedCallConv]` instead of `CallingConvention`. The SYSLIB1054 analyzer flags `DllImport` declarations that can convert.

code

csharp · 14 lines
csharp
#:property AllowUnsafeBlocks=true
using System.Runtime.InteropServices;

Console.WriteLine(Libc.strlen("héllo"));            // UTF-8: é is two bytes, so 6
Console.WriteLine(Libc.getpid() == Environment.ProcessId);

static partial class Libc
{
    [LibraryImport("libc", StringMarshalling = StringMarshalling.Utf8)]
    internal static partial nuint strlen(string s);

    [LibraryImport("libc")]
    internal static partial int getpid();
}

go deeper

for a junior

Know that DllImport and LibraryImport both call functions in native libraries, and that LibraryImport is the newer, source-generated form.

for a middle

Explain that DllImport's marshalling stub is generated and JIT-compiled at run time, while LibraryImport's is C# generated at build time for static partial methods.

for a senior

Migrate declarations: partial types, AllowUnsafeBlocks, explicit StringMarshalling, UnmanagedCallConv, and the SYSLIB1051/1062 errors that signal each missing piece.

for a principal

Set the interop policy for a codebase: new P/Invokes use LibraryImport, SYSLIB1054 is enforced, and exceptions stay as documented DllImport declarations.

## Two ways to call a native function **P/Invoke** (platform invoke) lets managed code call a function exported from a native library, such as `strlen` in the C library or a vendor SDK's DLL. The hard part is **marshalling**: converting managed arguments (strings, arrays, `bool`, structs) into the native representation and back. .NET offers two declarations for the same call: | | `[DllImport]` | `[LibraryImport]` | |---|---|---| | Declaration | `static extern` | `static partial` in a `partial` type | | Who writes the marshalling | The runtime, at run time | A source generator, at build time | | Form | An IL stub, JIT-compiled | C# source in the compilation | | Debuggable | Hard | Step through the generated code | | Strings by default | `CharSet.Ansi` behaviour | Must be stated explicitly | | Available | Always | .NET 7 and later | ## What DllImport does at run time When a `[DllImport]` method is first called, the runtime's interop system builds an **IL stub**, a method made of IL instructions that marshals each parameter according to the attribute's settings (`CharSet`, `SetLastError`, `[MarshalAs]`), calls the native entry point and marshals the result back. The stub is then JIT-compiled like any other method. That costs time on first call, needs run-time code generation, and leaves the marshalling invisible to the developer. ## What LibraryImport generates `LibraryImportAttribute` is consumed by a source generator included in the SDK and enabled by default. Per the attribute's own documentation, the generator only supplies an implementation for **static, partial, non-generic** methods, and only for C#. For each such method it generates, at build time: - code that converts managed arguments to native ones, pinning or allocating as needed; - an inner P/Invoke with only blittable parameters, such as `byte*`, that performs the actual native call; - code that converts the result back and cleans up. When every parameter is already blittable, as for `int getpid()`, the generator simply emits a plain `DllImport` for the partial method. The generated file appears in the compilation as `LibraryImports.g.cs` from `Microsoft.Interop.LibraryImportGenerator`, and `EmitCompilerGeneratedFiles` writes it to disk. Because the marshalling is ordinary compiled code, it needs no run-time stub generation, it can be inlined, and trimming and Native AOT see it like any other code. ## What a project must change 1. **`partial`, not `extern`.** The method becomes `static partial`, and the containing type must be `partial`; otherwise the compiler reports CS0751, "A partial member must be declared within a partial type." 2. **Unsafe code.** The generated code uses pointers, so the project needs `<AllowUnsafeBlocks>true</AllowUnsafeBlocks>`. Without it the build fails with SYSLIB1062. 3. **Explicit string marshalling.** There is no implicit ANSI behaviour. A `string` parameter without `StringMarshalling`, `StringMarshallingCustomType`, `[MarshalUsing]` or `[MarshalAs]` fails with SYSLIB1051. `StringMarshalling.Utf8` and `StringMarshalling.Utf16` are the first-class choices. 4. **Calling convention by attribute.** `CallingConvention` has no equivalent; use `[UnmanagedCallConv(CallConvs = new[] { typeof(CallConvStdcall) })]`. 5. **Windows-only fields are gone.** `ExactSpelling`, `PreserveSig`, `BestFitMapping` and `ThrowOnUnmappableChar` have no counterpart; `EntryPoint` must be the exact export name. `SetLastError` remains. ## Migrating in practice - The **SYSLIB1054** analyzer points at `DllImport` declarations that could use source generation, and a code fix converts many of them. - Types the generator cannot marshal produce **SYSLIB1051** or **SYSLIB1052**; for those, keep `DllImport` or write a custom marshaller with `[CustomMarshaller]`. - `DllImport` still works on .NET 10, and the Native AOT docs describe P/Invoke interop as working similarly in AOT and non-AOT apps; the gain from switching is compile-time, inspectable marshalling, not making an impossible call possible. ## Errors from native calls Many native APIs report failure through an error code set just before returning (`errno` on Unix-like systems, `SetLastError` on Windows). Setting `SetLastError = true` on either attribute makes the marshalling code capture that value immediately after the call, before other runtime work can overwrite it, and `Marshal.GetLastPInvokeError()` reads it afterwards. With `LibraryImport` that capture is visible in the generated code; with `DllImport` it happens inside the run-time stub. ## Common misunderstandings - `LibraryImport` does not change how the native library is found; library search rules are the same. - It is not "unsafe code in your source": the pointer code lives in the generated file, which is why the project-level switch is needed.

  • Why does LibraryImport require AllowUnsafeBlocks when your own code has no unsafe block?
    The generated implementation uses pointers to pin buffers and pass native pointers to the inner P/Invoke, and generated source is compiled under the project's settings. Without `<AllowUnsafeBlocks>true</AllowUnsafeBlocks>` the build reports SYSLIB1062 plus CS0227 errors pointing into the generated file.
  • What do you do when the generator cannot marshal a parameter type?
    The build reports SYSLIB1051 or SYSLIB1052 for that parameter. Either keep that one declaration as `[DllImport]`, change the signature to blittable types and convert in managed code, or write a custom marshaller marked with `[CustomMarshaller]` and reference it with `[MarshalUsing]`, so the generator emits your conversion.

  • LibraryImport loads the native library at compile time.
  • DllImport no longer works on .NET 10.
  • LibraryImport strings default to ANSI just like DllImport.
  • LibraryImport methods are declared static extern like DllImport ones.
  • Switching to LibraryImport changes how the runtime finds the native library.