.NET P/Invoke
Calling native code from .NET is powerful but unforgiving. Incorrect signatures, garbled strings, and leaked or freed memory are the most common sources of bugs — all can manifest as intermittent crashes, silent data corruption, or access violations far from the actual defect.
This skill covers both DllImport (available since .NET Framework 1.0) and LibraryImport (source-generated, .NET 7+). When targeting .NET Framework, always use DllImport. When targeting .NET 7+, prefer LibraryImport for new code. When native AOT is a requirement, LibraryImport is the only option.
When to Use This Skill
- Writing a new
[DllImport]or[LibraryImport]declaration from a C/C++ header - Reviewing P/Invoke signatures for correctness (type sizes, calling conventions, string encoding)
- Wrapping an entire C library for use from .NET
- Debugging
AccessViolationException,DllNotFoundException, or silent data corruption at the native boundary - Migrating
DllImportdeclarations toLibraryImportfor AOT/trimming compatibility - Diagnosing memory leaks or heap corruption involving native handles or buffers
Stop Signals
- Single function? Map the signature (Steps 1-3), handle strings/memory only if relevant, skip tooling and migration sections.
- Don't migrate existing
DllImporttoLibraryImportunless the user asks or AOT/trimming is an explicit requirement. - Don't recommend CsWin32 unless the target is specifically Win32 APIs.
- Don't generate callbacks (Step 8) unless the native API requires function pointers.
- Review request? Use the validation checklist — don't rewrite working code.
Inputs
Agent behavior: When documentation and native headers diverge, always trust the header. Online documentation (including official Win32 API docs) frequently omits or simplifies details about types, calling conventions, and struct layout that are critical for correct P/Invoke signatures.
Workflow
Step 1: Choose DllImport or LibraryImport
Step 2: Map Native Types to .NET Types
The most dangerous mappings — these cause the majority of bugs:
For the complete type mapping table, struct layout, and blittable type rules, see references/type-mapping.md [blocked].
❌ NEVER use
intorlongfor Clong— it's 32-bit on Windows, 64-bit on Unix. Always useCLong. ❌ NEVER useulongforsize_t— causes stack corruption on 32-bit. UsenuintorUIntPtr. ❌ NEVER useboolwithoutMarshalAs— the default marshal size is wrong.
Step 3: Write the Declaration
Given a C header:
DllImport:
LibraryImport:
Calling conventions only need to be specified when targeting Windows x86 (32-bit), where Cdecl and StdCall differ. On x64, ARM, and ARM64, there is a single calling convention and the attribute is unnecessary.
Agent behavior: If you detect that Windows x86 is a target — through project properties (e.g., <PlatformTarget>x86</PlatformTarget>), runtime identifiers (e.g., win-x86), build scripts, comments, or developer instructions — flag this to the developer and recommend explicit calling conventions on all P/Invoke declarations.
If the managed method name differs from the native export name, specify EntryPoint to avoid EntryPointNotFoundException:
Step 4: Handle Strings Correctly
- Know what encoding the native function expects. There is no safe default.
- Windows APIs: Always call the
W(UTF-16) variant. TheAvariant needs a specific reason and explicit ANSI encoding. - Cross-platform C libraries: Usually expect UTF-8.
- Specify encoding explicitly. Never rely on
CharSet.Auto. - Never introduce
StringBuilderfor output buffers.
❌ NEVER rely on
CharSet.Autoor omit string encoding — there is no safe default.
String lifetime warning: Marshalled strings are freed after the call returns. If native code stores the pointer (instead of copying), the lifetime must be manually managed. On Windows or .NET Framework, CoTaskMemAlloc/CoTaskMemFree is the first choice for cross-boundary ownership; on non-Windows targets, use NativeMemory APIs. The library may have its own allocator that must be used instead.
Step 5: Establish Memory Ownership
When memory crosses the boundary, exactly one side must own it — and both sides must agree.
❌ NEVER free with a mismatched allocator —
Marshal.FreeHGlobalonmalloc'd memory is heap corruption.
Model 1 — Caller allocates, caller frees (safest):
Model 2 — Callee allocates, caller frees (common in Win32):
Critical rule: Always free with the matching allocator. Never use Marshal.FreeHGlobal or Marshal.FreeCoTaskMem on malloc'd memory.
Model 3 — Handle-based (callee allocates, callee frees): Use SafeHandle (see Step 6).
Pinning managed objects — when native code stores the pointer or runs asynchronously:
Step 6: Use SafeHandle for Native Handles
Raw IntPtr leaks on exceptions and has no double-free protection. SafeHandle is non-negotiable.
Step 7: Handle Errors
Step 8: Handle Callbacks (if needed)
Preferred (.NET 8+): UnmanagedCallersOnly — avoids delegates entirely, no GC lifetime risk:
The method must be static, must not throw exceptions back to native code, and can only use blittable parameter types.
Fallback (older TFMs or when instance state is needed): delegate with rooting
If native code stores the function pointer, the delegate must stay rooted for its entire lifetime. A collected delegate means a crash.
GC.KeepAlive for short-lived callbacks: When converting a delegate to a function pointer with Marshal.GetFunctionPointerForDelegate, the GC does not track the relationship between the pointer and the delegate. Use GC.KeepAlive to prevent collection before the native call completes:
Cross-Platform Library Loading
Use NativeLibrary.SetDllImportResolver for complex scenarios, or conditional compilation for simple cases. Use CLong/CULong for C long/unsigned long. Note: CLong/CULong with LibraryImport requires [assembly: DisableRuntimeMarshalling].
Migrating DllImport to LibraryImport
For codebases targeting .NET 7+, migrating provides AOT compatibility and trimming safety.
- Add
partialto the containing class and make the methodstatic partial - Replace
[DllImport]with[LibraryImport] - Replace
CharSetwithStringMarshalling - Replace
SetLastError = truewithSetLastPInvokeError = true - Remove
CallingConventionunless targeting Windows x86 - Build and fix
SYSLIB1054–SYSLIB1057analyzer warnings
Enable the interop analyzers:
Tooling
CsWin32 (Win32 APIs)
For Win32 P/Invoke, prefer Microsoft.Windows.CsWin32 over hand-written signatures. It source-generates correct declarations from metadata. Add a NativeMethods.txt listing the APIs you need:
CsWinRT (WinRT APIs)
For WinRT interop, use Microsoft.Windows.CsWinRT to generate .NET projections from .winmd files.
Objective Sharpie (Objective-C APIs)
For binding Objective-C libraries (macOS/iOS), use Objective Sharpie to generate initial P/Invoke and binding definitions from Objective-C headers.
Validation
Review checklist
- Every signature matches the native header exactly (types, sizes)
- Calling convention specified if targeting Windows x86; omitted otherwise
- String encoding is explicit — no reliance on defaults or
CharSet.Auto - Memory ownership is documented and matched (who allocates, who frees, with what)
-
SafeHandleused for all native handles (no rawIntPtrescaping the interop layer) - Delegates passed as callbacks are rooted to prevent GC collection
-
SetLastError/SetLastPInvokeErrorset for APIs that use OS error codes - Struct layout matches native (packing, alignment, field order)
-
CLong/CULongused for Clong/unsigned longin cross-platform code - If using
CLong/CULongwithLibraryImport,[assembly: DisableRuntimeMarshalling]is applied - No
boolwithout explicitMarshalAs— always specifyUnmanagedType.Bool(4-byte) orUnmanagedType.U1(1-byte) to ensure normalization across the language boundary.
Runnable validation steps
- Build with interop analyzers enabled — confirm zero
SYSLIB1054–SYSLIB1057warnings: - Verify struct sizes match — for every struct crossing the boundary, assert
Marshal.SizeOf<T>()equals the nativesizeof - Round-trip test — call the native function with known inputs and verify expected outputs
- Test with non-ASCII strings — pass strings containing characters outside the ASCII range to confirm encoding is correct
Reference Files
- references/type-mapping.md [blocked] — Complete native-to-.NET type mapping table, struct layout patterns, blittable type rules. Load when encountering types not covered in Step 2 above, or when working with struct layout or blittable type questions.
- references/diagnostics.md [blocked] — Common pitfalls, failure modes and recovery, debugging approach, external resources. Load when debugging an existing P/Invoke failure or reviewing interop code for correctness issues.
