Aller au contenu
Skillpedia
API et serveurs (backend)5.8k · #14555

dotnet-pinvoke

Ce qu’il fait

Cette skill guide l'appel de bibliothèques de code natif depuis .NET avec P/Invoke et LibraryImport. Elle s'adresse aux développeurs .NET qui enveloppent ou déboguent des bibliothèques C ou C++ et doivent éviter les plantages et les fuites de mémoire.

Quand l’utiliser

  • ✓Quand vous écrivez une nouvelle déclaration de fonction native dans un projet .NET.
  • ✓Quand vous devez envelopper une bibliothèque C ou C++ pour l'utiliser depuis .NET.
  • ✓Quand vous déboguez des plantages ou des problèmes de mémoire à la frontière native.

Lien du skill

https://github.com/dotnet/skills/blob/main/plugins/dotnet-advanced/skills/dotnet-pinvoke/SKILL.md

Copiez-le et collez-le dans votre IA (Claude, ChatGPT ou Cursor) en lui demandant de suivre les instructions.

Comment l’utiliser

Le plus simple : copiez le message et collez-le dans votre IA. Elle lit le skill et suit les instructions.

Message prêt à coller

Utilise ce skill pour m’aider : https://github.com/dotnet/skills/blob/main/plugins/dotnet-advanced/skills/dotnet-pinvoke/SKILL.md Lis le fichier SKILL.md de ce lien et suis ses instructions pour ma tâche.
Envie que votre IA trouve seule des skills comme celui-ci ?Installez le MCP gratuit de Skillpedia : une ligne, et elle cherche parmi 15 000+ skills avant chaque tâche.Installer en 1 minute →

Exemple de demande à votre IA

“Enveloppe cette fonction C qui prend une chaîne et renvoie un tampon, pour que je puisse l'appeler depuis C#.”

5 nouveaux skills par semaine. 1 minute de lecture.

Comment ça marche

L'agent fait correspondre soigneusement la signature native, gère l'encodage des chaînes et la propriété de la mémoire, utilise des handles sûrs lorsque c'est nécessaire et vérifie l'exactitude des déclarations.

Contenu technique (SKILL.md original)

Texte original de l’auteur, en anglais, directement depuis GitHub.

.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 DllImport declarations to LibraryImport for 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 DllImport to LibraryImport unless 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

Input Required Description
Native header or documentation Yes C/C++ function signatures, struct definitions, calling conventions
Target framework Yes Determines whether to use DllImport or LibraryImport
Target platforms Recommended Affects type sizes (long, size_t) and library naming
Memory ownership contract Yes Who allocates and who frees each buffer or handle

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

Aspect DllImport LibraryImport (.NET 7+)
Mechanism Runtime marshalling Source generator (compile-time)
AOT / Trim safe No Yes
String marshalling CharSet enum StringMarshalling enum
Error handling SetLastError SetLastError
Availability .NET Framework 1.0+ .NET 7+ only

Step 2: Map Native Types to .NET Types

The most dangerous mappings — these cause the majority of bugs:

C / Win32 Type .NET Type Why
long CLong 32-bit on Windows, 64-bit on 64-bit Unix. With LibraryImport, requires [assembly: DisableRuntimeMarshalling]
size_t nuint / UIntPtr Pointer-sized. Use nuint on .NET 8+ and UIntPtr on earlier .NET. Never use ulong
BOOL (Win32) int Not bool — Win32 BOOL is 4 bytes
bool (C99) [MarshalAs(UnmanagedType.U1)] bool Must specify 1-byte marshal
HANDLE, HWND SafeHandle Prefer over raw IntPtr
LPWSTR / wchar_t* string UTF-16 on Windows (lowest cost for in strings). Avoid in cross-platform code — wchar_t width is compiler-defined (typically UTF-32 on non-Windows)
LPSTR / char* string Must specify encoding (ANSI or UTF-8). Always requires marshalling cost for in parameters

For the complete type mapping table, struct layout, and blittable type rules, see references/type-mapping.md.

❌ NEVER use int or long for C long — it's 32-bit on Windows, 64-bit on Unix. Always use CLong. ❌ NEVER use ulong for size_t — causes stack corruption on 32-bit. Use nuint or UIntPtr. ❌ NEVER use bool without MarshalAs — the default marshal size is wrong.

Step 3: Write the Declaration

Given a C header:

int32_t process_records(const Record* records, size_t count, uint32_t* out_processed);

DllImport:

[DllImport("mylib")]
Questions fréquentes

Quelle est la différence entre DllImport et LibraryImport ?

LibraryImport est généré par le compilateur et convient aux versions récentes de .NET, tandis que DllImport fonctionne sur .NET Framework.

Aide-t-elle contre les plantages ?

Oui. Elle couvre les causes courantes de violations d'accès, de fuites de mémoire et de données corrompues à la frontière native.

Couvre-t-elle les différentes plateformes ?

Oui. Elle couvre les schémas multiplateformes pour les appels natifs.

Détails

Description originale de l’auteur

Correctly call native (C/C++) libraries from .NET using P/Invoke and LibraryImport. Covers function signatures, string marshalling, memory lifetime, SafeHandle, and cross-platform patterns. USE FOR: writing new P/Invoke or LibraryImport declarations, reviewing or debugging existing native interop code, wrapping a C or C++ library for use in .NET, diagnosing crashes, memory leaks, or corruption at the managed/native boundary. DO NOT USE FOR: COM interop, C++/CLI mixed-mode assemblies, or pure managed code with no native dependencies.

repo: dotnet/skills

Popularité

Étoiles GitHub
5.8k
Position au classement
#14555
Licence
MIT
Mis à jour
02/11/2026

Ce skill vous est-il utile ?

0

Connectez-vous pour voter.

Commentaires

  • …

Autres skills de ce dépôt

Skills similaires