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。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 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.8k帮你的智能体创建 VS Code 自定义智能体文件,为每个智能体设置专属工具、指令以及向其他智能体的交接。
create-skill
5.8k帮你的智能体创建新的智能体技能,包括有效的名称、清晰的触发描述,以及符合标准的 SKILL.md 文件。
csharp-scripts
5.8k帮你的智能体通过 .NET 命令行工具以单个文件运行小型 C# 程序,无需创建完整项目。
nuget-trusted-publishing
5.8k帮你的智能体设置 GitHub Actions 的 NuGet 可信发布,让包使用短期令牌发布,而不是保存的 API 密钥。