dotnet-pinvoke
できること
このスキルは、P/InvokeとLibraryImportを使い、ネイティブのコードのライブラリを.NETから呼び出す方法を導きます。C言語やC++のライブラリを包んだりデバッグしたりする.NETの開発者が、クラッシュやメモリリークを避けるためのものです。
使う場面
- ✓.NETのプロジェクトに、新しいネイティブ関数の宣言を書くとき。
- ✓C言語またはC++のライブラリを、.NETから使えるように包む必要があるとき。
- ✓ネイティブとの境界でのクラッシュやメモリの問題をデバッグしているとき。
スキルのリンク
https://github.com/dotnet/skills/blob/main/plugins/dotnet-advanced/skills/dotnet-pinvoke/SKILL.mdコピーしてAI(Claude、ChatGPT、Cursor)に貼り付け、指示に従うよう頼んでください。
使い方
いちばん簡単な方法:メッセージをコピーしてAIに貼り付けるだけ。AIがスキルを読んで指示に従います。
貼り付け用メッセージ
Claude Code、Codex、Cursorの場合:プロジェクトのフォルダで実行するとスキルがインストールされます。
SKILL.mdをダウンロードして、エージェントのスキル用フォルダに入れてください。
AIへの頼み方の例
“文字列を受け取ってバッファを返すこのC関数を、C#から呼べるように包んでください。”
毎週5つの新しいスキル。1分で読めます。
仕組み
エージェントは、ネイティブの署名を慎重に対応づけ、文字列のエンコードとメモリの所有権を扱い、必要なところで安全なハンドルを使い、宣言が正しいかを確認します。
技術的な内容(元のSKILL.md)
作者による元のテキスト(英語)を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
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
| 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
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:
int32_t process_records(const Record* records, size_t count, uint32_t* out_processed);
DllImport:
[DllImport("mylib")]
よくある質問
DllImportとLibraryImportの違いは何ですか?
LibraryImportはソースから生成され新しい.NETに向いており、DllImportは.NET Frameworkでも動きます。
クラッシュの役に立ちますか?
はい。ネイティブとの境界でのアクセス違反、メモリリーク、データの破損の一般的な原因を扱います。
異なるプラットフォームも扱いますか?
はい。ネイティブの呼び出しのためのプラットフォームをまたぐパターンを扱います。
詳細
作者による元の説明
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
人気
- GitHubのスター
- 5.8k
- ランキング
- #14555
- ライセンス
- MIT
- 更新日
- 2026/11/2
コメント
- …
このリポジトリの他のスキル
create-custom-agent
5.8kVisual Studio Codeのカスタムエージェントのファイルを、独自のツール、指示、ほかのエージェントへの引き継ぎとともに作るようエージェントを支援します。
create-skill
5.8k有効な名前、明確な発動の説明、規格に従うSKILL.mdファイルを持つ、新しいエージェントのスキルを作るようエージェントを支援します。
csharp-scripts
5.8k.NETのコマンドラインツールを使って、完全なプロジェクトを作らずに、小さなC#のプログラムを一つのファイルとして実行するようエージェントを支援します。
nuget-trusted-publishing
5.8kGitHub Actionsから、NuGetの信頼された公開を設定するようエージェントを支援します。APIキーを保存せず、短期間有効なトークンでパッケージを公開できるようにします。
似ているスキル
api-connector-builder
280kエージェントが既存のパターンに従って、新しいAPI連携を構築します。新しい方式を作らずに、もう一つ連携を追加したいときに使います。
api-design
280kエージェントがベストプラクティスに沿ってREST APIを設計できるようにします。APIの通信方法、エラーの表示方法、データの整理方法を決めるのに役立ちます。
backend-patterns
280kエージェントのサーバーサイドのアーキテクチャパターンとデータベースの最適化を支援します。サーバー上で動くコードを作成またはレビューするときに役立ちます。