dotnet-native-interop
dotnet-native-interop
Platform Invoke (P/Invoke) patterns for calling native C/C++ libraries from .NET: [LibraryImport] (preferred, .NET 7+) vs [DllImport] (legacy), struct marshalling, string marshalling, function pointer callbacks, NativeLibrary.SetDllImportResolver for cross-platform library resolution, and platform-specific considerations for Windows, macOS, Linux, iOS, and Android.
Version assumptions: .NET 7.0+ baseline for [LibraryImport]. [DllImport] available in all .NET versions. NativeLibrary API available since .NET Core 3.0.
Scope boundary: This skill owns general P/Invoke guidance -- declaring native method signatures, marshalling data types, resolving library paths across platforms, and callback patterns. AOT-specific P/Invoke concerns (direct pinvoke, compile-time marshalling for AOT publishing) are in [skill:dotnet-native-aot]. Windows COM interop and CsWin32 source generator usage are in [skill:dotnet-winui]. WASM has no traditional P/Invoke support -- see [skill:dotnet-aot-wasm] for JavaScript interop via [JSImport]/[JSExport].
Out of scope: COM interop (Windows legacy). CsWin32 source generator -- see [skill:dotnet-winui]. JNI bridge for Android Java interop (different mechanism from P/Invoke). [JSImport]/[JSExport] for WASM -- see [skill:dotnet-aot-wasm].
Cross-references: [skill:dotnet-native-aot] for AOT-specific P/Invoke and [LibraryImport] in publish scenarios, [skill:dotnet-aot-architecture] for AOT-first design patterns including source-generated interop, [skill:dotnet-winui] for CsWin32 source generator and COM interop, [skill:dotnet-aot-wasm] for WASM JavaScript interop (not native P/Invoke).
LibraryImport vs DllImport
[LibraryImport] (.NET 7+) is the preferred attribute for new P/Invoke declarations. It uses source generation to produce marshalling code at compile time, making it fully AOT-compatible and eliminating runtime codegen overhead.
[DllImport] is the legacy attribute. It relies on runtime marshalling, which may require codegen not available in AOT scenarios. Use [DllImport] only when targeting .NET 6 or earlier, or when the SYSLIB1054 analyzer indicates [LibraryImport] cannot handle a specific signature.