dotnet-pinvoke
O que ela faz
Esta skill orienta a chamada de bibliotecas de código nativo a partir do .NET usando P/Invoke e LibraryImport. É para desenvolvedores de .NET que encapsulam ou depuram bibliotecas em C ou C++ e precisam evitar travamentos e vazamentos de memória.
Quando usar
- ✓Quando você escreve uma nova declaração de função nativa em um projeto .NET.
- ✓Quando você precisa encapsular uma biblioteca em C ou C++ para usar no .NET.
- ✓Quando você está depurando travamentos ou problemas de memória na fronteira nativa.
Link da skill
https://github.com/dotnet/skills/blob/main/plugins/dotnet-advanced/skills/dotnet-pinvoke/SKILL.mdCopie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.
Como usar
O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.
Mensagem pronta para colar
Para Claude Code, Codex ou Cursor: rode na pasta do projeto e a skill fica instalada.
Baixe o SKILL.md e coloque na pasta de skills do seu agente.
Exemplo do que pedir para a IA
“Encapsule esta função em C que recebe uma string e retorna um buffer para que eu possa chamá-la em C#.”
5 skills novas por semana. 1 minuto de leitura.
Como funciona
O agente mapeia a assinatura nativa com cuidado, trata a codificação de strings e a posse da memória, usa handles seguros quando necessário e verifica se as declarações estão corretas.
Conteúdo técnico (SKILL.md original)
Texto original do autor, em inglês, direto do 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")]
Perguntas frequentes
Qual a diferença entre DllImport e LibraryImport?
LibraryImport é gerado pelo código-fonte e serve para versões mais novas do .NET, enquanto DllImport funciona no .NET Framework.
Ela ajuda com travamentos?
Sim. Ela cobre causas comuns de violação de acesso, vazamento de memória e dados corrompidos na fronteira nativa.
Ela cobre diferentes plataformas?
Sim. Ela cobre padrões multiplataforma para chamadas nativas.
Detalhes
Descrição original do autor
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
Popularidade
- Estrelas no GitHub
- 5,8 mil
- Posição no ranking
- #14555
- Licença
- MIT
- Atualizada em
- 02/11/2026
Comentários
- …
Mais skills deste repositório
create-custom-agent
5,8 milAjuda seu agente a criar arquivos de agentes personalizados para o VS Code, com suas próprias ferramentas, instruções e transferências para outros agentes.
create-skill
5,8 milAjuda seu agente a criar uma nova skill de agente com nome válido, uma descrição clara de quando usá-la e um arquivo SKILL.md que segue o padrão.
csharp-scripts
5,8 milAjuda seu agente a rodar um pequeno programa C# como um único arquivo com a ferramenta de linha de comando do .NET, sem criar um projeto completo.
nuget-trusted-publishing
5,8 milAjuda seu agente a configurar a publicação confiável do NuGet pelo GitHub Actions, usando tokens de curta duração em vez de chaves de API armazenadas.
Skills parecidas
api-connector-builder
280 milFaz seu agente construir novas conexões com APIs seguindo o padrão já existente. Use quando precisar adicionar mais uma integração sem criar um novo jeito de fazer.
api-design
280 milAjuda seu agente a projetar APIs REST seguindo as melhores práticas. É útil para definir como as APIs se comunicam, como os erros são mostrados e como organizar os dados.
backend-patterns
280 milAjuda seu agente com padrões de arquitetura do lado do servidor e otimização de banco de dados. É útil para construir ou revisar o código que roda no servidor.