Zum Inhalt springen
Skillpedia
APIs & Server (Backend)5.8k · #14555

dotnet-pinvoke

Was er macht

Dieser Skill führt beim Aufruf nativer Code-Bibliotheken aus .NET über P/Invoke und LibraryImport. Er ist für .NET-Entwickler, die C- oder C++-Bibliotheken kapseln oder debuggen und Abstürze sowie Speicherlecks vermeiden müssen.

Wann du ihn nutzt

  • ✓Wenn du in einem .NET-Projekt eine neue native Funktionsdeklaration schreibst.
  • ✓Wenn du eine C- oder C++-Bibliothek für die Nutzung aus .NET kapseln musst.
  • ✓Wenn du Abstürze oder Speicherprobleme an der Grenze zum nativen Code debuggst.

Link zum Skill

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

Kopiere ihn und füge ihn in deine KI ein (Claude, ChatGPT oder Cursor) mit der Bitte, den Anweisungen zu folgen.

So nutzt du ihn

Am einfachsten: Kopiere die Nachricht und füge sie in deine KI ein. Sie liest den Skill und folgt den Anweisungen.

Fertige Nachricht zum Einfügen

Nutze diesen Skill, um mir zu helfen: https://github.com/dotnet/skills/blob/main/plugins/dotnet-advanced/skills/dotnet-pinvoke/SKILL.md Lies die SKILL.md unter diesem Link und folge ihren Anweisungen für meine Aufgabe.
Soll deine KI Skills wie diesen selbst finden?Installiere den kostenlosen Skillpedia-MCP: eine Zeile, und sie durchsucht vor jeder Aufgabe 15.000+ Skills.In 1 Minute installieren →

Beispielanfrage an deine KI

“Kapsle diese C-Funktion, die eine Zeichenkette entgegennimmt und einen Puffer zurückgibt, damit ich sie aus C# aufrufen kann.”

5 neue Skills pro Woche. 1 Minute Lesezeit.

So funktioniert es

Der Agent bildet die native Signatur sorgfältig ab, behandelt Zeichenkodierung und Speicherbesitz, nutzt bei Bedarf sichere Handles und prüft die Deklarationen auf Korrektheit.

Technischer Inhalt (originale SKILL.md)

Originaltext des Autors, auf Englisch, direkt von 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")]
Häufige Fragen

Was ist der Unterschied zwischen DllImport und LibraryImport?

LibraryImport wird vom Quellgenerator erzeugt und passt zu neueren .NET-Versionen, während DllImport auch mit .NET Framework funktioniert.

Hilft es bei Abstürzen?

Ja. Es behandelt typische Ursachen wie Zugriffsverletzungen, Speicherlecks und beschädigte Daten an der nativen Grenze.

Deckt es verschiedene Plattformen ab?

Ja. Es behandelt plattformübergreifende Muster für native Aufrufe.

Details

Originalbeschreibung des Autors

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

Beliebtheit

GitHub-Sterne
5.8k
Platz im Ranking
#14555
Lizenz
MIT
Aktualisiert
2.11.2026

Ist dieser Skill nützlich?

0

Anmelden um abzustimmen.

Kommentare

  • …

Weitere Skills aus diesem Repository

Ähnliche Skills