LibraryImport & Source-Generated P/Invoke
Use [LibraryImport] (C# 11+) for AOT-compatible, source-generated marshaling that outperforms DllImport.
Why LibraryImport?
[LibraryImport] was introduced in .NET 7 (C# 11) as a source-generated, AOT-compatible replacement for [DllImport]. The classic DllImport relies on runtime marshaling via reflection — problematic for Native AOT. LibraryImport emits all marshaling code at compile time.
Declaring a LibraryImport Method
Mark a static partial method with [LibraryImport]. The source generator fills in the implementation. You must also mark the containing class partial.
using System.Runtime.InteropServices;
internal static partial class NativeMethods
{
// Source generator creates the P/Invoke body at compile time
[LibraryImport("mylib", EntryPoint = "add_integers")]
internal static partial int AddIntegers(int a, int b);
// String marshaling must be explicit in LibraryImport
[LibraryImport("mylib", StringMarshalling = StringMarshalling.Utf8)]
internal static partial int ProcessString(string text);
}All lessons in this course
- P/Invoke Fundamentals
- LibraryImport & Source-Generated P/Invoke
- Unsafe Code, Pointers & Fixed Buffers
- COM Interop & Runtime Callable Wrappers