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.8k에이전트가 자체 도구, 지침, 다른 에이전트로의 핸드오프를 가진 VS Code 커스텀 에이전트 파일을 만들도록 돕습니다.
create-skill
5.8k에이전트가 올바른 이름, 명확한 트리거 설명, 표준을 따르는 SKILL.md 파일로 새 에이전트 스킬을 만들도록 돕습니다.
csharp-scripts
5.8k에이전트가 .NET 명령줄 도구로 작은 C# 프로그램을 전체 프로젝트 없이 단일 파일로 실행하도록 돕습니다.
nuget-trusted-publishing
5.8k에이전트가 GitHub Actions에서 NuGet 신뢰 게시를 설정하도록 돕습니다. 저장된 API 키 대신 수명이 짧은 토큰으로 패키지를 게시합니다.
비슷한 스킬
api-connector-builder
280k에이전트가 기존 패턴을 따라 새로운 API 연결을 만들도록 합니다. 새로운 방식을 도입하지 않고 연동을 하나 더 추가할 때 씁니다.
api-design
280k에이전트가 모범 사례에 따라 REST API를 설계하도록 돕습니다. API가 통신하는 방식, 오류를 보여 주는 방식, 데이터를 정리하는 방식을 정하는 데 유용합니다.
backend-patterns
280k에이전트가 서버 쪽 아키텍처 패턴과 데이터베이스 최적화를 다루도록 돕습니다. 서버에서 실행되는 코드를 만들거나 검토할 때 유용합니다.