본문으로 건너뛰기
Skillpedia
API 및 서버 (백엔드)5.8k · #14555

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가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/dotnet/skills/blob/main/plugins/dotnet-advanced/skills/dotnet-pinvoke/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

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 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")]
자주 묻는 질문

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.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬