[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6DZBJS17BEJ37FCHV2Q51MH":3,"skill-same:01M6DZBJS17BEJ37FCHV2Q51MH":86},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":46,"linkOnly":47,"markdownContent":48,"markdownBody":49,"frontMatter":50,"refName":52,"commitSha":53,"skillDirectory":54,"forksCount":55,"repositoryHtmlUrl":56,"repositoryHomepageUrl":57,"ownerHtmlUrl":58,"ownerBlogUrl":59,"ownerDescription":60,"updatedAt":61,"install":62,"resources":75},"01M6DZBJS17BEJ37FCHV2Q51MH","dotnet-pinvoke",null,"Correctly call native (C\u002FC++) libraries from .NET using P\u002FInvoke and LibraryImport. Covers function signatures, string marshalling, memory lifetime, SafeHandle, and cross-platform patterns. USE FOR: writing new P\u002FInvoke 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\u002Fnative boundary. DO NOT USE FOR: COM interop, C++\u002FCLI mixed-mode assemblies, or pure managed code with no native dependencies.","managedcode\u002Fdotnet-skills","managedcode","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F78253589?v=4","01M6DYDJR3EG8KB5G4PC65XCTT","Managed Code","01M6DYDJX0ZT432N04NYJW89DN",514,"MIT","https:\u002F\u002Fgithub.com\u002Fmanagedcode\u002Fdotnet-skills\u002Fblob\u002Fmain\u002Fexternal-sources\u002Fupstreams\u002Fdotnet-skills\u002Fplugins\u002Fdotnet-advanced\u002Fskills\u002Fdotnet-pinvoke\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45],"dotnet","dotnet pinvoke","call","new","invoke","managed","at","mode","native","STRING","platform","c++","cross-platform","dependencies","signatures","writing","patterns","do","use","boundary","marshalling","library","code","libraries","debugging","memory","cli","2026-11-10 10:12:30",false,"---\nname: dotnet-pinvoke\ndescription: >\n  Correctly call native (C\u002FC++) libraries from .NET using P\u002FInvoke and LibraryImport.\n  Covers function signatures, string marshalling, memory lifetime, SafeHandle, and\n  cross-platform patterns.\n  USE FOR: writing new P\u002FInvoke or LibraryImport declarations, reviewing or debugging\n  existing native interop code, wrapping a C or C++ library for use in .NET, diagnosing\n  crashes, memory leaks, or corruption at the managed\u002Fnative boundary.\n  DO NOT USE FOR: COM interop, C++\u002FCLI mixed-mode assemblies, or pure managed code with\n  no native dependencies.\nlicense: MIT\n---\n\n# .NET P\u002FInvoke\n\nCalling 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.\n\nThis 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.\n\n## When to Use This Skill\n\n- Writing a new `[DllImport]` or `[LibraryImport]` declaration from a C\u002FC++ header\n- Reviewing P\u002FInvoke signatures for correctness (type sizes, calling conventions, string encoding)\n- Wrapping an entire C library for use from .NET\n- Debugging `AccessViolationException`, `DllNotFoundException`, or silent data corruption at the native boundary\n- Migrating `DllImport` declarations to `LibraryImport` for AOT\u002Ftrimming compatibility\n- Diagnosing memory leaks or heap corruption involving native handles or buffers\n\n## Stop Signals\n\n- **Single function?** Map the signature (Steps 1-3), handle strings\u002Fmemory only if relevant, skip tooling and migration sections.\n- **Don't migrate** existing `DllImport` to `LibraryImport` unless the user asks or AOT\u002Ftrimming is an explicit requirement.\n- **Don't recommend CsWin32** unless the target is specifically Win32 APIs.\n- **Don't generate callbacks** (Step 8) unless the native API requires function pointers.\n- **Review request?** Use the validation checklist — don't rewrite working code.\n\n## Inputs\n\n| Input | Required | Description |\n|-------|----------|-------------|\n| Native header or documentation | Yes | C\u002FC++ function signatures, struct definitions, calling conventions |\n| Target framework | Yes | Determines whether to use `DllImport` or `LibraryImport` |\n| Target platforms | Recommended | Affects type sizes (`long`, `size_t`) and library naming |\n| Memory ownership contract | Yes | Who allocates and who frees each buffer or handle |\n\n**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\u002FInvoke signatures.\n\n---\n\n## Workflow\n\n### Step 1: Choose DllImport or LibraryImport\n\n| Aspect | `DllImport` | `LibraryImport` (.NET 7+) |\n|--------|-------------|---------------------------|\n| **Mechanism** | Runtime marshalling | Source generator (compile-time) |\n| **AOT \u002F Trim safe** | No | Yes |\n| **String marshalling** | `CharSet` enum | `StringMarshalling` enum |\n| **Error handling** | `SetLastError` | `SetLastError` |\n| **Availability** | .NET Framework 1.0+ | .NET 7+ only |\n\n### Step 2: Map Native Types to .NET Types\n\nThe most dangerous mappings — these cause the majority of bugs:\n\n| C \u002F Win32 Type | .NET Type | Why |\n|----------------|-----------|-----|\n| `long` | **`CLong`** | 32-bit on Windows, 64-bit on 64-bit Unix. With `LibraryImport`, requires `[assembly: DisableRuntimeMarshalling]` |\n| `size_t` | `nuint` \u002F `UIntPtr` | Pointer-sized. Use `nuint` on .NET 8+ and `UIntPtr` on earlier .NET. Never use `ulong` |\n| `BOOL` (Win32) | `int` | Not `bool` — Win32 `BOOL` is 4 bytes |\n| `bool` (C99) | `[MarshalAs(UnmanagedType.U1)] bool` | Must specify 1-byte marshal |\n| `HANDLE`, `HWND` | `SafeHandle` | Prefer over raw `IntPtr` |\n| `LPWSTR` \u002F `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) |\n| `LPSTR` \u002F `char*` | `string` | Must specify encoding (ANSI or UTF-8). Always requires marshalling cost for `in` parameters |\n\n**For the complete type mapping table, struct layout, and blittable type rules**, see [references\u002Ftype-mapping.md](references\u002Ftype-mapping.md).\n\n> ❌ **NEVER** use `int` or `long` for C `long` — it's 32-bit on Windows, 64-bit on Unix. Always use `CLong`.\n> ❌ **NEVER** use `ulong` for `size_t` — causes stack corruption on 32-bit. Use `nuint` or `UIntPtr`.\n> ❌ **NEVER** use `bool` without `MarshalAs` — the default marshal size is wrong.\n\n### Step 3: Write the Declaration\n\nGiven a C header:\n\n```c\nint32_t process_records(const Record* records, size_t count, uint32_t* out_processed);\n```\n\n**DllImport:**\n\n```csharp\n[DllImport(\"mylib\")]\nprivate static extern int ProcessRecords(\n    [In] Record[] records, UIntPtr count, out uint outProcessed);\n```\n\n**LibraryImport:**\n\n```csharp\n[LibraryImport(\"mylib\")]\ninternal static partial int ProcessRecords(\n    [In] Record[] records, nuint count, out uint outProcessed);\n```\n\nCalling conventions only need to be specified when targeting Windows x86 (32-bit), where `Cdecl` and `StdCall` differ. On x64, ARM, and ARM64, there is a single calling convention and the attribute is unnecessary.\n\n**Agent behavior:** If you detect that Windows x86 is a target — through project properties (e.g., `\u003CPlatformTarget>x86\u003C\u002FPlatformTarget>`), runtime identifiers (e.g., `win-x86`), build scripts, comments, or developer instructions — flag this to the developer and recommend explicit calling conventions on all P\u002FInvoke declarations.\n\n```csharp\n\u002F\u002F DllImport (x86 targets)\n[DllImport(\"mylib\", CallingConvention = CallingConvention.Cdecl)]\n\n\u002F\u002F LibraryImport (x86 targets)\n[LibraryImport(\"mylib\")]\n[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]\n```\n\nIf the managed method name differs from the native export name, specify `EntryPoint` to avoid `EntryPointNotFoundException`:\n\n```csharp\n\u002F\u002F DllImport\n[DllImport(\"mylib\", EntryPoint = \"process_records\")]\nprivate static extern int ProcessRecords(\n    [In] Record[] records, UIntPtr count, out uint outProcessed);\n\n\u002F\u002F LibraryImport\n[LibraryImport(\"mylib\", EntryPoint = \"process_records\")]\ninternal static partial int ProcessRecords(\n    [In] Record[] records, nuint count, out uint outProcessed);\n```\n\n### Step 4: Handle Strings Correctly\n\n1. **Know what encoding the native function expects.** There is no safe default.\n2. **Windows APIs:** Always call the `W` (UTF-16) variant. The `A` variant needs a specific reason and explicit ANSI encoding.\n3. **Cross-platform C libraries:** Usually expect UTF-8.\n4. **Specify encoding explicitly.** Never rely on `CharSet.Auto`.\n5. **Never introduce `StringBuilder` for output buffers.**\n\n> ❌ **NEVER** rely on `CharSet.Auto` or omit string encoding — there is no safe default.\n\n```csharp\n\u002F\u002F DllImport — Windows API (UTF-16)\n[DllImport(\"kernel32.dll\", CharSet = CharSet.Unicode, SetLastError = true)]\nprivate static extern int GetModuleFileNameW(\n    IntPtr hModule, [Out] char[] filename, int size);\n\n\u002F\u002F DllImport — Cross-platform C library (UTF-8)\n[DllImport(\"mylib\")]\nprivate static extern int SetName(\n    [MarshalAs(UnmanagedType.LPUTF8Str)] string name);\n\n\u002F\u002F LibraryImport — UTF-16\n[LibraryImport(\"kernel32\", StringMarshalling = StringMarshalling.Utf16,\n    SetLastError = true)]\ninternal static partial int GetModuleFileNameW(\n    IntPtr hModule, [Out] char[] filename, int size);\n\n\u002F\u002F LibraryImport — UTF-8\n[LibraryImport(\"mylib\", StringMarshalling = StringMarshalling.Utf8)]\ninternal static partial int SetName(string name);\n```\n\n**String lifetime warning:** Marshalled strings are freed after the call returns. If native code stores the pointer (instead of copying), the lifetime must be manually managed. On Windows or .NET Framework, `CoTaskMemAlloc`\u002F`CoTaskMemFree` is the first choice for cross-boundary ownership; on non-Windows targets, use `NativeMemory` APIs. The library may have its own allocator that must be used instead.\n\n### Step 5: Establish Memory Ownership\n\nWhen memory crosses the boundary, exactly one side must own it — and both sides must agree.\n\n> ❌ **NEVER** free with a mismatched allocator — `Marshal.FreeHGlobal` on `malloc`'d memory is heap corruption.\n\n**Model 1 — Caller allocates, caller frees (safest):**\n\n```csharp\n[LibraryImport(\"mylib\")]\nprivate static partial int GetName(\n    Span\u003Cbyte> buffer, nuint bufferSize, out nuint actualSize);\n\npublic static string GetName()\n{\n    Span\u003Cbyte> buffer = stackalloc byte[256];\n    int result = GetName(buffer, (nuint)buffer.Length, out nuint actualSize);\n    if (result != 0) throw new InvalidOperationException($\"Failed: {result}\");\n    return Encoding.UTF8.GetString(buffer[..(int)actualSize]);\n}\n```\n\n**Model 2 — Callee allocates, caller frees (common in Win32):**\n\n```csharp\n[LibraryImport(\"mylib\")]\nprivate static partial IntPtr GetVersion();\n[LibraryImport(\"mylib\")]\nprivate static partial void FreeString(IntPtr s);\n\npublic static string GetVersion()\n{\n    IntPtr ptr = GetVersion();\n    try { return Marshal.PtrToStringUTF8(ptr) ?? throw new InvalidOperationException(); }\n    finally { FreeString(ptr); } \u002F\u002F Must use the library's own free function\n}\n```\n\n**Critical rule:** Always free with the matching allocator. Never use `Marshal.FreeHGlobal` or `Marshal.FreeCoTaskMem` on `malloc`'d memory.\n\n**Model 3 — Handle-based (callee allocates, callee frees):** Use `SafeHandle` (see Step 6).\n\n**Pinning managed objects** — when native code stores the pointer or runs asynchronously:\n\n```csharp\n\u002F\u002F Synchronous: use fixed\npublic static unsafe void ProcessSync(byte[] data)\n{\n    fixed (byte* ptr = data) { ProcessData(ptr, (nuint)data.Length); }\n}\n\n\u002F\u002F Asynchronous: use GCHandle\nvar gcHandle = GCHandle.Alloc(data, GCHandleType.Pinned);\n\u002F\u002F Must keep pinned until native processing completes, then call gcHandle.Free()\n```\n\n### Step 6: Use SafeHandle for Native Handles\n\nRaw `IntPtr` leaks on exceptions and has no double-free protection. `SafeHandle` is non-negotiable.\n\n```csharp\ninternal sealed class MyLibHandle : SafeHandleZeroOrMinusOneIsInvalid\n{\n    \u002F\u002F Required by the marshalling infrastructure to instantiate the handle.\n    \u002F\u002F Do not remove — there are no direct callers.\n    private MyLibHandle() : base(ownsHandle: true) { }\n\n    [LibraryImport(\"mylib\", StringMarshalling = StringMarshalling.Utf8)]\n    private static partial MyLibHandle CreateHandle(string config);\n\n    [LibraryImport(\"mylib\")]\n    private static partial int UseHandle(MyLibHandle h, ReadOnlySpan\u003Cbyte> data, nuint len);\n\n    [LibraryImport(\"mylib\")]\n    private static partial void DestroyHandle(IntPtr h);\n\n    protected override bool ReleaseHandle() { DestroyHandle(handle); return true; }\n\n    public static MyLibHandle Create(string config)\n    {\n        var h = CreateHandle(config);\n        if (h.IsInvalid) throw new InvalidOperationException(\"Failed to create handle\");\n        return h;\n    }\n\n    public int Use(ReadOnlySpan\u003Cbyte> data) => UseHandle(this, data, (nuint)data.Length);\n}\n\n\u002F\u002F Usage: SafeHandle is IDisposable\nusing var handle = MyLibHandle.Create(\"config=value\");\nint result = handle.Use(myData);\n```\n\n### Step 7: Handle Errors\n\nSet `LibraryImportAttribute.SetLastError` to `true` when the native API's contract requires capturing the OS last-error value, then retrieve it with `Marshal.GetLastPInvokeError()`.\n\n```csharp\n\u002F\u002F Win32 APIs — check SetLastError\n[LibraryImport(\"kernel32\", SetLastError = true)]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static partial bool CloseHandle(IntPtr hObject);\n\nif (!CloseHandle(handle))\n    throw new Win32Exception(Marshal.GetLastPInvokeError());\n\n\u002F\u002F HRESULT APIs\nint hr = NativeDoWork(context);\nMarshal.ThrowExceptionForHR(hr);\n```\n\n### Step 8: Handle Callbacks (if needed)\n\n**Preferred (.NET 8+): `UnmanagedCallersOnly`** — avoids delegates entirely, no GC lifetime risk:\n\n```csharp\n[UnmanagedCallersOnly]\nprivate static void LogCallback(int level, IntPtr message)\n{\n    string msg = Marshal.PtrToStringUTF8(message) ?? string.Empty;\n    Console.WriteLine($\"[{level}] {msg}\");\n}\n\n[LibraryImport(\"mylib\")]\nprivate static unsafe partial void SetLogCallback(\n    delegate* unmanaged\u003Cint, IntPtr, void> cb);\n\nunsafe { SetLogCallback(&LogCallback); }\n```\n\nThe method must be `static`, must not throw exceptions back to native code, and can only use blittable parameter types.\n\n**Fallback (older TFMs or when instance state is needed): delegate with rooting**\n\n```csharp\n[UnmanagedFunctionPointer(CallingConvention.Cdecl)] \u002F\u002F Only needed on Windows x86\nprivate delegate void LogCallbackDelegate(int level, IntPtr message);\n\n\u002F\u002F CRITICAL: prevent delegate from being garbage collected\nprivate static LogCallbackDelegate? s_logCallback;\n\npublic static void EnableLogging(Action\u003Cint, string> handler)\n{\n    s_logCallback = (level, msgPtr) =>\n    {\n        string msg = Marshal.PtrToStringUTF8(msgPtr) ?? string.Empty;\n        handler(level, msg);\n    };\n    SetLogCallback(s_logCallback);\n}\n```\n\nIf native code stores the function pointer, the delegate **must** stay rooted for its entire lifetime. A collected delegate means a crash.\n\n**`GC.KeepAlive` for short-lived callbacks:** When converting a delegate to a function pointer with `Marshal.GetFunctionPointerForDelegate`, the GC does not track the relationship between the pointer and the delegate. Use `GC.KeepAlive` to prevent collection before the native call completes:\n\n```csharp\nvar callback = new LogCallbackDelegate((level, msgPtr) =>\n{\n    string msg = Marshal.PtrToStringUTF8(msgPtr) ?? string.Empty;\n    Console.WriteLine($\"[{level}] {msg}\");\n});\n\nIntPtr fnPtr = Marshal.GetFunctionPointerForDelegate(callback);\nNativeUsesCallback(fnPtr);\nGC.KeepAlive(callback); \u002F\u002F prevent collection — fnPtr does not root the delegate\n```\n\n---\n\n## Cross-Platform Library Loading\n\nUse `NativeLibrary.SetDllImportResolver` for complex scenarios, or conditional compilation for simple cases. Use `CLong`\u002F`CULong` for C `long`\u002F`unsigned long`. Note: `CLong`\u002F`CULong` with `LibraryImport` requires `[assembly: DisableRuntimeMarshalling]`.\n\n```csharp\n\u002F\u002F Trivial: use platform naming convention\n\u002F\u002F The default naming convention adds corresponding prefix and extension when\n\u002F\u002F searching the nativelibrary. The resultant file name will be mylib.dll on\n\u002F\u002F Windows, libmylib.so on Linux and libmylib.dylib on macOS.\nprivate const string LibName = \"mylib\";\n\n\u002F\u002F Simple: conditional compilation\n\u002F\u002F WINDOWS, LINUX, MACOS are predefined only when targeting an OS-specific TFM\n\u002F\u002F (e.g., net8.0-windows). For portable TFMs (e.g., net8.0), these symbols are\n\u002F\u002F not defined — use the runtime resolver approach below instead.\n#if WINDOWS\n    private const string LibName = \"mylib.dll\";\n#elif LINUX\n    private const string LibName = \"libmylib.so\";\n#elif MACOS\n    private const string LibName = \"libmylib.dylib\";\n#endif\n\n\u002F\u002F Complex: runtime resolver\n\u002F\u002F When targeting netstandard2.0 or other frameworks when OperatingSystem.IsXXX\n\u002F\u002F is not available, use RuntimeInformation.IsOSPlatform(OSPlatform.XXX) api.\nNativeLibrary.SetDllImportResolver(typeof(MyLib).Assembly,\n    (name, assembly, searchPath) =>\n    {\n        if (name != \"mylib\") return IntPtr.Zero;\n        string libName = OperatingSystem.IsWindows()\n            ? \"mylib.dll\"\n            : OperatingSystem.IsMacOS()\n                ? \"libmylib.dylib\" : \"libmylib.so\";\n        NativeLibrary.TryLoad(libName, assembly, searchPath, out var handle);\n        return handle;\n    });\n```\n\n---\n\n## Migrating DllImport to LibraryImport\n\nFor codebases targeting .NET 7+, migrating provides AOT compatibility and trimming safety.\n\n1. Add `partial` to the containing class and make the method `static partial`\n2. Replace `[DllImport]` with `[LibraryImport]`\n3. Replace `CharSet` with `StringMarshalling`\n4. Preserve `SetLastError = true` for APIs that require capturing the OS last-error value\n5. Remove `CallingConvention` unless targeting Windows x86\n6. Build and fix `SYSLIB1054`–`SYSLIB1057` analyzer warnings\n\nEnable the interop analyzers:\n\n```xml\n\u003CPropertyGroup>\n    \u003CEnableTrimAnalyzer>true\u003C\u002FEnableTrimAnalyzer>\n    \u003CEnableAotAnalyzer>true\u003C\u002FEnableAotAnalyzer>\n\u003C\u002FPropertyGroup>\n```\n\n---\n\n## Tooling\n\n### CsWin32 (Win32 APIs)\n\nFor Win32 P\u002FInvoke, prefer [Microsoft.Windows.CsWin32](https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FCsWin32) over hand-written signatures. It source-generates correct declarations from metadata. Add a `NativeMethods.txt` listing the APIs you need:\n\n```bash\ndotnet add package Microsoft.Windows.CsWin32\n```\n\n### CsWinRT (WinRT APIs)\n\nFor WinRT interop, use [Microsoft.Windows.CsWinRT](https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FCsWinRT) to generate .NET projections from `.winmd` files.\n\n### Objective Sharpie (Objective-C APIs)\n\nFor binding Objective-C libraries (macOS\u002FiOS), use [Objective Sharpie](https:\u002F\u002Flearn.microsoft.com\u002Fprevious-versions\u002Fxamarin\u002Fcross-platform\u002Fmacios\u002Fbinding\u002Fobjective-sharpie) to generate initial P\u002FInvoke and binding definitions from Objective-C headers.\n\n---\n\n## Validation\n\n### Review checklist\n\n- [ ] Every signature matches the native header exactly (types, sizes)\n- [ ] Calling convention specified if targeting Windows x86; omitted otherwise\n- [ ] String encoding is explicit — no reliance on defaults or `CharSet.Auto`\n- [ ] Memory ownership is documented and matched (who allocates, who frees, with what)\n- [ ] `SafeHandle` used for all native handles (no raw `IntPtr` escaping the interop layer)\n- [ ] Delegates passed as callbacks are rooted to prevent GC collection\n- [ ] `DllImportAttribute.SetLastError` or `LibraryImportAttribute.SetLastError` set to `true` when the native API requires last-error capture\n- [ ] Struct layout matches native (packing, alignment, field order)\n- [ ] `CLong`\u002F`CULong` used for C `long`\u002F`unsigned long` in cross-platform code\n- [ ] If using `CLong`\u002F`CULong` with `LibraryImport`, `[assembly: DisableRuntimeMarshalling]` is applied\n- [ ] No `bool` without explicit `MarshalAs` — always specify `UnmanagedType.Bool` (4-byte) or `UnmanagedType.U1` (1-byte) to ensure normalization across the language boundary.\n\n### Runnable validation steps\n\n1. **Build with interop analyzers enabled** — confirm zero `SYSLIB1054`–`SYSLIB1057` warnings:\n   ```xml\n   \u003CEnableTrimAnalyzer>true\u003C\u002FEnableTrimAnalyzer>\n   \u003CEnableAotAnalyzer>true\u003C\u002FEnableAotAnalyzer>\n   ```\n2. **Verify struct sizes match** — for every struct crossing the boundary, assert `Marshal.SizeOf\u003CT>()` equals the native `sizeof`\n3. **Round-trip test** — call the native function with known inputs and verify expected outputs\n4. **Test with non-ASCII strings** — pass strings containing characters outside the ASCII range to confirm encoding is correct\n\n## Reference Files\n\n- **[references\u002Ftype-mapping.md](references\u002Ftype-mapping.md)** — Complete native-to-.NET type mapping table, struct layout patterns, blittable type rules. **Load when** encountering types not covered in Step 2 above, or when working with struct layout or blittable type questions.\n- **[references\u002Fdiagnostics.md](references\u002Fdiagnostics.md)** — Common pitfalls, failure modes and recovery, debugging approach, external resources. **Load when** debugging an existing P\u002FInvoke failure or reviewing interop code for correctness issues.\n","# .NET P\u002FInvoke\n\nCalling 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.\n\nThis 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.\n\n## When to Use This Skill\n\n- Writing a new `[DllImport]` or `[LibraryImport]` declaration from a C\u002FC++ header\n- Reviewing P\u002FInvoke signatures for correctness (type sizes, calling conventions, string encoding)\n- Wrapping an entire C library for use from .NET\n- Debugging `AccessViolationException`, `DllNotFoundException`, or silent data corruption at the native boundary\n- Migrating `DllImport` declarations to `LibraryImport` for AOT\u002Ftrimming compatibility\n- Diagnosing memory leaks or heap corruption involving native handles or buffers\n\n## Stop Signals\n\n- **Single function?** Map the signature (Steps 1-3), handle strings\u002Fmemory only if relevant, skip tooling and migration sections.\n- **Don't migrate** existing `DllImport` to `LibraryImport` unless the user asks or AOT\u002Ftrimming is an explicit requirement.\n- **Don't recommend CsWin32** unless the target is specifically Win32 APIs.\n- **Don't generate callbacks** (Step 8) unless the native API requires function pointers.\n- **Review request?** Use the validation checklist — don't rewrite working code.\n\n## Inputs\n\n| Input | Required | Description |\n|-------|----------|-------------|\n| Native header or documentation | Yes | C\u002FC++ function signatures, struct definitions, calling conventions |\n| Target framework | Yes | Determines whether to use `DllImport` or `LibraryImport` |\n| Target platforms | Recommended | Affects type sizes (`long`, `size_t`) and library naming |\n| Memory ownership contract | Yes | Who allocates and who frees each buffer or handle |\n\n**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\u002FInvoke signatures.\n\n---\n\n## Workflow\n\n### Step 1: Choose DllImport or LibraryImport\n\n| Aspect | `DllImport` | `LibraryImport` (.NET 7+) |\n|--------|-------------|---------------------------|\n| **Mechanism** | Runtime marshalling | Source generator (compile-time) |\n| **AOT \u002F Trim safe** | No | Yes |\n| **String marshalling** | `CharSet` enum | `StringMarshalling` enum |\n| **Error handling** | `SetLastError` | `SetLastError` |\n| **Availability** | .NET Framework 1.0+ | .NET 7+ only |\n\n### Step 2: Map Native Types to .NET Types\n\nThe most dangerous mappings — these cause the majority of bugs:\n\n| C \u002F Win32 Type | .NET Type | Why |\n|----------------|-----------|-----|\n| `long` | **`CLong`** | 32-bit on Windows, 64-bit on 64-bit Unix. With `LibraryImport`, requires `[assembly: DisableRuntimeMarshalling]` |\n| `size_t` | `nuint` \u002F `UIntPtr` | Pointer-sized. Use `nuint` on .NET 8+ and `UIntPtr` on earlier .NET. Never use `ulong` |\n| `BOOL` (Win32) | `int` | Not `bool` — Win32 `BOOL` is 4 bytes |\n| `bool` (C99) | `[MarshalAs(UnmanagedType.U1)] bool` | Must specify 1-byte marshal |\n| `HANDLE`, `HWND` | `SafeHandle` | Prefer over raw `IntPtr` |\n| `LPWSTR` \u002F `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) |\n| `LPSTR` \u002F `char*` | `string` | Must specify encoding (ANSI or UTF-8). Always requires marshalling cost for `in` parameters |\n\n**For the complete type mapping table, struct layout, and blittable type rules**, see [references\u002Ftype-mapping.md](references\u002Ftype-mapping.md).\n\n> ❌ **NEVER** use `int` or `long` for C `long` — it's 32-bit on Windows, 64-bit on Unix. Always use `CLong`.\n> ❌ **NEVER** use `ulong` for `size_t` — causes stack corruption on 32-bit. Use `nuint` or `UIntPtr`.\n> ❌ **NEVER** use `bool` without `MarshalAs` — the default marshal size is wrong.\n\n### Step 3: Write the Declaration\n\nGiven a C header:\n\n```c\nint32_t process_records(const Record* records, size_t count, uint32_t* out_processed);\n```\n\n**DllImport:**\n\n```csharp\n[DllImport(\"mylib\")]\nprivate static extern int ProcessRecords(\n    [In] Record[] records, UIntPtr count, out uint outProcessed);\n```\n\n**LibraryImport:**\n\n```csharp\n[LibraryImport(\"mylib\")]\ninternal static partial int ProcessRecords(\n    [In] Record[] records, nuint count, out uint outProcessed);\n```\n\nCalling conventions only need to be specified when targeting Windows x86 (32-bit), where `Cdecl` and `StdCall` differ. On x64, ARM, and ARM64, there is a single calling convention and the attribute is unnecessary.\n\n**Agent behavior:** If you detect that Windows x86 is a target — through project properties (e.g., `\u003CPlatformTarget>x86\u003C\u002FPlatformTarget>`), runtime identifiers (e.g., `win-x86`), build scripts, comments, or developer instructions — flag this to the developer and recommend explicit calling conventions on all P\u002FInvoke declarations.\n\n```csharp\n\u002F\u002F DllImport (x86 targets)\n[DllImport(\"mylib\", CallingConvention = CallingConvention.Cdecl)]\n\n\u002F\u002F LibraryImport (x86 targets)\n[LibraryImport(\"mylib\")]\n[UnmanagedCallConv(CallConvs = [typeof(CallConvCdecl)])]\n```\n\nIf the managed method name differs from the native export name, specify `EntryPoint` to avoid `EntryPointNotFoundException`:\n\n```csharp\n\u002F\u002F DllImport\n[DllImport(\"mylib\", EntryPoint = \"process_records\")]\nprivate static extern int ProcessRecords(\n    [In] Record[] records, UIntPtr count, out uint outProcessed);\n\n\u002F\u002F LibraryImport\n[LibraryImport(\"mylib\", EntryPoint = \"process_records\")]\ninternal static partial int ProcessRecords(\n    [In] Record[] records, nuint count, out uint outProcessed);\n```\n\n### Step 4: Handle Strings Correctly\n\n1. **Know what encoding the native function expects.** There is no safe default.\n2. **Windows APIs:** Always call the `W` (UTF-16) variant. The `A` variant needs a specific reason and explicit ANSI encoding.\n3. **Cross-platform C libraries:** Usually expect UTF-8.\n4. **Specify encoding explicitly.** Never rely on `CharSet.Auto`.\n5. **Never introduce `StringBuilder` for output buffers.**\n\n> ❌ **NEVER** rely on `CharSet.Auto` or omit string encoding — there is no safe default.\n\n```csharp\n\u002F\u002F DllImport — Windows API (UTF-16)\n[DllImport(\"kernel32.dll\", CharSet = CharSet.Unicode, SetLastError = true)]\nprivate static extern int GetModuleFileNameW(\n    IntPtr hModule, [Out] char[] filename, int size);\n\n\u002F\u002F DllImport — Cross-platform C library (UTF-8)\n[DllImport(\"mylib\")]\nprivate static extern int SetName(\n    [MarshalAs(UnmanagedType.LPUTF8Str)] string name);\n\n\u002F\u002F LibraryImport — UTF-16\n[LibraryImport(\"kernel32\", StringMarshalling = StringMarshalling.Utf16,\n    SetLastError = true)]\ninternal static partial int GetModuleFileNameW(\n    IntPtr hModule, [Out] char[] filename, int size);\n\n\u002F\u002F LibraryImport — UTF-8\n[LibraryImport(\"mylib\", StringMarshalling = StringMarshalling.Utf8)]\ninternal static partial int SetName(string name);\n```\n\n**String lifetime warning:** Marshalled strings are freed after the call returns. If native code stores the pointer (instead of copying), the lifetime must be manually managed. On Windows or .NET Framework, `CoTaskMemAlloc`\u002F`CoTaskMemFree` is the first choice for cross-boundary ownership; on non-Windows targets, use `NativeMemory` APIs. The library may have its own allocator that must be used instead.\n\n### Step 5: Establish Memory Ownership\n\nWhen memory crosses the boundary, exactly one side must own it — and both sides must agree.\n\n> ❌ **NEVER** free with a mismatched allocator — `Marshal.FreeHGlobal` on `malloc`'d memory is heap corruption.\n\n**Model 1 — Caller allocates, caller frees (safest):**\n\n```csharp\n[LibraryImport(\"mylib\")]\nprivate static partial int GetName(\n    Span\u003Cbyte> buffer, nuint bufferSize, out nuint actualSize);\n\npublic static string GetName()\n{\n    Span\u003Cbyte> buffer = stackalloc byte[256];\n    int result = GetName(buffer, (nuint)buffer.Length, out nuint actualSize);\n    if (result != 0) throw new InvalidOperationException($\"Failed: {result}\");\n    return Encoding.UTF8.GetString(buffer[..(int)actualSize]);\n}\n```\n\n**Model 2 — Callee allocates, caller frees (common in Win32):**\n\n```csharp\n[LibraryImport(\"mylib\")]\nprivate static partial IntPtr GetVersion();\n[LibraryImport(\"mylib\")]\nprivate static partial void FreeString(IntPtr s);\n\npublic static string GetVersion()\n{\n    IntPtr ptr = GetVersion();\n    try { return Marshal.PtrToStringUTF8(ptr) ?? throw new InvalidOperationException(); }\n    finally { FreeString(ptr); } \u002F\u002F Must use the library's own free function\n}\n```\n\n**Critical rule:** Always free with the matching allocator. Never use `Marshal.FreeHGlobal` or `Marshal.FreeCoTaskMem` on `malloc`'d memory.\n\n**Model 3 — Handle-based (callee allocates, callee frees):** Use `SafeHandle` (see Step 6).\n\n**Pinning managed objects** — when native code stores the pointer or runs asynchronously:\n\n```csharp\n\u002F\u002F Synchronous: use fixed\npublic static unsafe void ProcessSync(byte[] data)\n{\n    fixed (byte* ptr = data) { ProcessData(ptr, (nuint)data.Length); }\n}\n\n\u002F\u002F Asynchronous: use GCHandle\nvar gcHandle = GCHandle.Alloc(data, GCHandleType.Pinned);\n\u002F\u002F Must keep pinned until native processing completes, then call gcHandle.Free()\n```\n\n### Step 6: Use SafeHandle for Native Handles\n\nRaw `IntPtr` leaks on exceptions and has no double-free protection. `SafeHandle` is non-negotiable.\n\n```csharp\ninternal sealed class MyLibHandle : SafeHandleZeroOrMinusOneIsInvalid\n{\n    \u002F\u002F Required by the marshalling infrastructure to instantiate the handle.\n    \u002F\u002F Do not remove — there are no direct callers.\n    private MyLibHandle() : base(ownsHandle: true) { }\n\n    [LibraryImport(\"mylib\", StringMarshalling = StringMarshalling.Utf8)]\n    private static partial MyLibHandle CreateHandle(string config);\n\n    [LibraryImport(\"mylib\")]\n    private static partial int UseHandle(MyLibHandle h, ReadOnlySpan\u003Cbyte> data, nuint len);\n\n    [LibraryImport(\"mylib\")]\n    private static partial void DestroyHandle(IntPtr h);\n\n    protected override bool ReleaseHandle() { DestroyHandle(handle); return true; }\n\n    public static MyLibHandle Create(string config)\n    {\n        var h = CreateHandle(config);\n        if (h.IsInvalid) throw new InvalidOperationException(\"Failed to create handle\");\n        return h;\n    }\n\n    public int Use(ReadOnlySpan\u003Cbyte> data) => UseHandle(this, data, (nuint)data.Length);\n}\n\n\u002F\u002F Usage: SafeHandle is IDisposable\nusing var handle = MyLibHandle.Create(\"config=value\");\nint result = handle.Use(myData);\n```\n\n### Step 7: Handle Errors\n\nSet `LibraryImportAttribute.SetLastError` to `true` when the native API's contract requires capturing the OS last-error value, then retrieve it with `Marshal.GetLastPInvokeError()`.\n\n```csharp\n\u002F\u002F Win32 APIs — check SetLastError\n[LibraryImport(\"kernel32\", SetLastError = true)]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static partial bool CloseHandle(IntPtr hObject);\n\nif (!CloseHandle(handle))\n    throw new Win32Exception(Marshal.GetLastPInvokeError());\n\n\u002F\u002F HRESULT APIs\nint hr = NativeDoWork(context);\nMarshal.ThrowExceptionForHR(hr);\n```\n\n### Step 8: Handle Callbacks (if needed)\n\n**Preferred (.NET 8+): `UnmanagedCallersOnly`** — avoids delegates entirely, no GC lifetime risk:\n\n```csharp\n[UnmanagedCallersOnly]\nprivate static void LogCallback(int level, IntPtr message)\n{\n    string msg = Marshal.PtrToStringUTF8(message) ?? string.Empty;\n    Console.WriteLine($\"[{level}] {msg}\");\n}\n\n[LibraryImport(\"mylib\")]\nprivate static unsafe partial void SetLogCallback(\n    delegate* unmanaged\u003Cint, IntPtr, void> cb);\n\nunsafe { SetLogCallback(&LogCallback); }\n```\n\nThe method must be `static`, must not throw exceptions back to native code, and can only use blittable parameter types.\n\n**Fallback (older TFMs or when instance state is needed): delegate with rooting**\n\n```csharp\n[UnmanagedFunctionPointer(CallingConvention.Cdecl)] \u002F\u002F Only needed on Windows x86\nprivate delegate void LogCallbackDelegate(int level, IntPtr message);\n\n\u002F\u002F CRITICAL: prevent delegate from being garbage collected\nprivate static LogCallbackDelegate? s_logCallback;\n\npublic static void EnableLogging(Action\u003Cint, string> handler)\n{\n    s_logCallback = (level, msgPtr) =>\n    {\n        string msg = Marshal.PtrToStringUTF8(msgPtr) ?? string.Empty;\n        handler(level, msg);\n    };\n    SetLogCallback(s_logCallback);\n}\n```\n\nIf native code stores the function pointer, the delegate **must** stay rooted for its entire lifetime. A collected delegate means a crash.\n\n**`GC.KeepAlive` for short-lived callbacks:** When converting a delegate to a function pointer with `Marshal.GetFunctionPointerForDelegate`, the GC does not track the relationship between the pointer and the delegate. Use `GC.KeepAlive` to prevent collection before the native call completes:\n\n```csharp\nvar callback = new LogCallbackDelegate((level, msgPtr) =>\n{\n    string msg = Marshal.PtrToStringUTF8(msgPtr) ?? string.Empty;\n    Console.WriteLine($\"[{level}] {msg}\");\n});\n\nIntPtr fnPtr = Marshal.GetFunctionPointerForDelegate(callback);\nNativeUsesCallback(fnPtr);\nGC.KeepAlive(callback); \u002F\u002F prevent collection — fnPtr does not root the delegate\n```\n\n---\n\n## Cross-Platform Library Loading\n\nUse `NativeLibrary.SetDllImportResolver` for complex scenarios, or conditional compilation for simple cases. Use `CLong`\u002F`CULong` for C `long`\u002F`unsigned long`. Note: `CLong`\u002F`CULong` with `LibraryImport` requires `[assembly: DisableRuntimeMarshalling]`.\n\n```csharp\n\u002F\u002F Trivial: use platform naming convention\n\u002F\u002F The default naming convention adds corresponding prefix and extension when\n\u002F\u002F searching the nativelibrary. The resultant file name will be mylib.dll on\n\u002F\u002F Windows, libmylib.so on Linux and libmylib.dylib on macOS.\nprivate const string LibName = \"mylib\";\n\n\u002F\u002F Simple: conditional compilation\n\u002F\u002F WINDOWS, LINUX, MACOS are predefined only when targeting an OS-specific TFM\n\u002F\u002F (e.g., net8.0-windows). For portable TFMs (e.g., net8.0), these symbols are\n\u002F\u002F not defined — use the runtime resolver approach below instead.\n#if WINDOWS\n    private const string LibName = \"mylib.dll\";\n#elif LINUX\n    private const string LibName = \"libmylib.so\";\n#elif MACOS\n    private const string LibName = \"libmylib.dylib\";\n#endif\n\n\u002F\u002F Complex: runtime resolver\n\u002F\u002F When targeting netstandard2.0 or other frameworks when OperatingSystem.IsXXX\n\u002F\u002F is not available, use RuntimeInformation.IsOSPlatform(OSPlatform.XXX) api.\nNativeLibrary.SetDllImportResolver(typeof(MyLib).Assembly,\n    (name, assembly, searchPath) =>\n    {\n        if (name != \"mylib\") return IntPtr.Zero;\n        string libName = OperatingSystem.IsWindows()\n            ? \"mylib.dll\"\n            : OperatingSystem.IsMacOS()\n                ? \"libmylib.dylib\" : \"libmylib.so\";\n        NativeLibrary.TryLoad(libName, assembly, searchPath, out var handle);\n        return handle;\n    });\n```\n\n---\n\n## Migrating DllImport to LibraryImport\n\nFor codebases targeting .NET 7+, migrating provides AOT compatibility and trimming safety.\n\n1. Add `partial` to the containing class and make the method `static partial`\n2. Replace `[DllImport]` with `[LibraryImport]`\n3. Replace `CharSet` with `StringMarshalling`\n4. Preserve `SetLastError = true` for APIs that require capturing the OS last-error value\n5. Remove `CallingConvention` unless targeting Windows x86\n6. Build and fix `SYSLIB1054`–`SYSLIB1057` analyzer warnings\n\nEnable the interop analyzers:\n\n```xml\n\u003CPropertyGroup>\n    \u003CEnableTrimAnalyzer>true\u003C\u002FEnableTrimAnalyzer>\n    \u003CEnableAotAnalyzer>true\u003C\u002FEnableAotAnalyzer>\n\u003C\u002FPropertyGroup>\n```\n\n---\n\n## Tooling\n\n### CsWin32 (Win32 APIs)\n\nFor Win32 P\u002FInvoke, prefer [Microsoft.Windows.CsWin32](https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FCsWin32) over hand-written signatures. It source-generates correct declarations from metadata. Add a `NativeMethods.txt` listing the APIs you need:\n\n```bash\ndotnet add package Microsoft.Windows.CsWin32\n```\n\n### CsWinRT (WinRT APIs)\n\nFor WinRT interop, use [Microsoft.Windows.CsWinRT](https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002FCsWinRT) to generate .NET projections from `.winmd` files.\n\n### Objective Sharpie (Objective-C APIs)\n\nFor binding Objective-C libraries (macOS\u002FiOS), use [Objective Sharpie](https:\u002F\u002Flearn.microsoft.com\u002Fprevious-versions\u002Fxamarin\u002Fcross-platform\u002Fmacios\u002Fbinding\u002Fobjective-sharpie) to generate initial P\u002FInvoke and binding definitions from Objective-C headers.\n\n---\n\n## Validation\n\n### Review checklist\n\n- [ ] Every signature matches the native header exactly (types, sizes)\n- [ ] Calling convention specified if targeting Windows x86; omitted otherwise\n- [ ] String encoding is explicit — no reliance on defaults or `CharSet.Auto`\n- [ ] Memory ownership is documented and matched (who allocates, who frees, with what)\n- [ ] `SafeHandle` used for all native handles (no raw `IntPtr` escaping the interop layer)\n- [ ] Delegates passed as callbacks are rooted to prevent GC collection\n- [ ] `DllImportAttribute.SetLastError` or `LibraryImportAttribute.SetLastError` set to `true` when the native API requires last-error capture\n- [ ] Struct layout matches native (packing, alignment, field order)\n- [ ] `CLong`\u002F`CULong` used for C `long`\u002F`unsigned long` in cross-platform code\n- [ ] If using `CLong`\u002F`CULong` with `LibraryImport`, `[assembly: DisableRuntimeMarshalling]` is applied\n- [ ] No `bool` without explicit `MarshalAs` — always specify `UnmanagedType.Bool` (4-byte) or `UnmanagedType.U1` (1-byte) to ensure normalization across the language boundary.\n\n### Runnable validation steps\n\n1. **Build with interop analyzers enabled** — confirm zero `SYSLIB1054`–`SYSLIB1057` warnings:\n   ```xml\n   \u003CEnableTrimAnalyzer>true\u003C\u002FEnableTrimAnalyzer>\n   \u003CEnableAotAnalyzer>true\u003C\u002FEnableAotAnalyzer>\n   ```\n2. **Verify struct sizes match** — for every struct crossing the boundary, assert `Marshal.SizeOf\u003CT>()` equals the native `sizeof`\n3. **Round-trip test** — call the native function with known inputs and verify expected outputs\n4. **Test with non-ASCII strings** — pass strings containing characters outside the ASCII range to confirm encoding is correct\n\n## Reference Files\n\n- **[references\u002Ftype-mapping.md](references\u002Ftype-mapping.md)** — Complete native-to-.NET type mapping table, struct layout patterns, blittable type rules. **Load when** encountering types not covered in Step 2 above, or when working with struct layout or blittable type questions.\n- **[references\u002Fdiagnostics.md](references\u002Fdiagnostics.md)** — Common pitfalls, failure modes and recovery, debugging approach, external resources. **Load when** debugging an existing P\u002FInvoke failure or reviewing interop code for correctness issues.\n",{"name":5,"license":15,"description":51},"Correctly call native (C\u002FC++) libraries from .NET using P\u002FInvoke and LibraryImport. Covers function signatures, string marshalling, memory lifetime, SafeHandle, and cross-platform patterns. USE FOR: writing new P\u002FInvoke 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\u002Fnative boundary. DO NOT USE FOR: COM interop, C++\u002FCLI mixed-mode assemblies, or pure managed code with no native dependencies.\n","main","497cc9aba79a931ac6fb8d36a48cc22fe3d6d74b","external-sources\u002Fupstreams\u002Fdotnet-skills\u002Fplugins\u002Fdotnet-advanced\u002Fskills\u002Fdotnet-pinvoke",41,"https:\u002F\u002Fgithub.com\u002Fmanagedcode\u002Fdotnet-skills","https:\u002F\u002Fskills.managed-code.com","https:\u002F\u002Fgithub.com\u002Fmanagedcode","https:\u002F\u002Fwww.managed-code.com","Open Source Community for .NET Developers: Reliable, Actively Maintained, and Community-Driven. Made in Ukraine 🇺🇦 with ❤️","2026-11-12 19:59:36",{"source":8,"skillName":5,"commands":63,"prompt":73,"zipAvailable":74},[64,67,70],{"tool":65,"command":66},"npx","npx skills add managedcode\u002Fdotnet-skills --skill dotnet-pinvoke",{"tool":68,"command":69},"bunx","bunx skills add managedcode\u002Fdotnet-skills --skill dotnet-pinvoke",{"tool":71,"command":72},"pnpm","pnpm dlx skills add managedcode\u002Fdotnet-skills --skill dotnet-pinvoke","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmanagedcode\u002Fdotnet-skills\u002Fblob\u002Fmain\u002Fexternal-sources\u002Fupstreams\u002Fdotnet-skills\u002Fplugins\u002Fdotnet-advanced\u002Fskills\u002Fdotnet-pinvoke\u002FSKILL.md",true,[76,82],{"path":77,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":80,"sourceHtmlUrl":81},"references\u002Fdiagnostics.md","REFERENCE","参考文档",3732,"https:\u002F\u002Fgithub.com\u002Fmanagedcode\u002Fdotnet-skills\u002Fblob\u002Fmain\u002Fexternal-sources\u002Fupstreams\u002Fdotnet-skills\u002Fplugins\u002Fdotnet-advanced\u002Fskills\u002Fdotnet-pinvoke\u002Freferences\u002Fdiagnostics.md",{"path":83,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":84,"sourceHtmlUrl":85},"references\u002Ftype-mapping.md",3058,"https:\u002F\u002Fgithub.com\u002Fmanagedcode\u002Fdotnet-skills\u002Fblob\u002Fmain\u002Fexternal-sources\u002Fupstreams\u002Fdotnet-skills\u002Fplugins\u002Fdotnet-advanced\u002Fskills\u002Fdotnet-pinvoke\u002Freferences\u002Ftype-mapping.md",[87,123,146,177,187,213],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":103,"publishedAt":46},"01M6DYQE1Y9FHAQHEDTVFQ3447","xtwitter-scraper","Use XTwitterScraper when a .NET application needs typed access to Xquik's X automation REST API for tweet search, user lookup, posting workflows, extraction jobs, monitors, webhooks, or giveaway draws. USE FOR: integrating the XTwitterScraper NuGet package; reviewing Xquik API client usage; modeling API-key configuration, pagination, binary exports, raw responses, retries, and webhook\u002Fevent flows in .NET. DO NOT USE FOR: unrelated stacks; direct browser automation; generic social-media strategy; or code that does not call Xquik. INVOKES: inspect the repository context, edit targeted files, and run relevant build, test, lint, or validation commands when changes are made.","https:\u002F\u002Fgithub.com\u002Fmanagedcode\u002Fdotnet-skills\u002Fblob\u002Fmain\u002Fcatalog\u002FLibraries\u002FXTwitterScraper\u002Fskills\u002Fxtwitter-scraper\u002FSKILL.md",[93,98],{"categoryNo":94,"categoryName":95,"taxonomyType":96,"taxonomyTypeDesc":97},"01JBSEEDCAT000000000000010","后端与接口","SCENARIO","使用场景",{"categoryNo":99,"categoryName":100,"taxonomyType":101,"taxonomyTypeDesc":102},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[104,105,106,107,41,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122],"xtwitter scraper","browser automation","workflows","run","browser","search","repository","api","Media","api client","access","edit","unrelated","webhooks","files","social","commands","modeling","webhook",{"skillNo":124,"name":125,"nameZh":6,"description":126,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":127,"categories":128,"keywords":135,"publishedAt":46},"01M6DYQ9S4PE1H6G8MCH9T21HR","sep","Use Sep for high-performance separated-value parsing and writing in .NET, including delimiter inference, explicit parser\u002Fwriter options, and low-allocation row\u002Fcolumn workflows. USE FOR: delimited data needs are performance-sensitive and allocation-aware; project needs explicit control over separator inference, escaping, trimming, and header behavior;. DO NOT USE FOR: unrelated stacks; generic tasks that do not need this specific guidance. INVOKES: inspect the repository context, edit targeted files, and run relevant build, test, lint, or validation commands when changes are made.","https:\u002F\u002Fgithub.com\u002Fmanagedcode\u002Fdotnet-skills\u002Fblob\u002Fmain\u002Fcatalog\u002FLibraries\u002FSep\u002Fskills\u002Fsep\u002FSKILL.md",[129,132],{"categoryNo":130,"categoryName":131,"taxonomyType":96,"taxonomyTypeDesc":97},"01JBSEEDCAT000000000000018","写作与文案",{"categoryNo":133,"categoryName":134,"taxonomyType":101,"taxonomyTypeDesc":102},"01JBSEEDCAT000000000000036","内容创作者",[125,34,136,106,137,107,110,138,139,140,115,141,116,118,36,142,143,144,120,145],"performance","tasks","data","parsing","parser","context","writer","options","project","high-performance",{"skillNo":147,"name":148,"nameZh":6,"description":149,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":150,"categories":151,"keywords":152,"publishedAt":46},"01M6DZS2DNEPXCGGF6SSCW6G5V","webgpu-threejs-tsl","Comprehensive guide for developing WebGPU-enabled Three.js applications using TSL (Three.js Shading Language). Covers WebGPU renderer setup, TSL syntax and node materials, compute shaders, post-processing effects, and WGSL integration. Use this skill when working with Three.js WebGPU, TSL shaders, node materials, or GPU compute in Three.js.","https:\u002F\u002Fgithub.com\u002Fmanagedcode\u002Fdotnet-skills\u002Fblob\u002Fmain\u002Fexternal-sources\u002Fupstreams\u002Fwebgpu-claude-skill\u002Fskills\u002Fwebgpu-threejs-tsl\u002FSKILL.md",[],[153,154,155,156,157,158,159,160,161,162,163,164,37,165,166,167,168,169,170,171,172,173,174,175,176],"webgpu","threejs","webgpu threejs tsl","setup","shaders","gpu","integration","applications","js","node","syntax","guide","language","three","compute","post","processing","with","renderer","for","materials","wgsl","effects","when",{"skillNo":178,"name":179,"nameZh":6,"description":180,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":181,"categories":182,"keywords":183,"publishedAt":46},"01M6DZS0BQXW2B56A289XF1X76","roslynk","Use Roslynk for semantic inspection and edits of *.cs, *.razor and *.cshtml solution files.","https:\u002F\u002Fgithub.com\u002Fmanagedcode\u002Fdotnet-skills\u002Fblob\u002Fmain\u002Fexternal-sources\u002Fupstreams\u002Froslynk\u002Fskills\u002Froslynk\u002FSKILL.md",[],[179,37,118,184,185,172,186],"semantic","razor","inspection",{"skillNo":188,"name":189,"nameZh":6,"description":190,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":191,"categories":192,"keywords":193,"publishedAt":46},"01M6DZRW6MEJCVW80K3S4XV60K","system-text-json-net11","Imperative guidance for the System.Text.Json APIs added in .NET 11: the built-in `JsonNamingPolicy.PascalCase` naming policy, and the strongly-typed generic `JsonSerializerOptions.GetTypeInfo` and `JsonSerializerOptions.TryGetTypeInfo` metadata accessors (generic overloads that return a typed `JsonTypeInfo`). USE ONLY when the user is targeting net11.0 or later and needs PascalCase JSON property or dictionary-key names without writing a custom naming policy, a strongly-typed generic `JsonTypeInfo` instead of the non-generic `JsonTypeInfo`, or a no-throw way to probe whether a type's serialization metadata is resolved. DO NOT USE when the target is earlier than net11.0, the requested behavior uses an established pre-net11 naming policy, or the user explicitly selected another JSON library.","https:\u002F\u002Fgithub.com\u002Fmanagedcode\u002Fdotnet-skills\u002Fblob\u002Fmain\u002Fexternal-sources\u002Fupstreams\u002Fdotnet-skills\u002Fplugins\u002Fdotnet11\u002Fskills\u002Fsystem-text-json-net11\u002FSKILL.md",[],[194,195,196,197,34,198,199,40,200,201,202,37,203,204,205,206,36,207,208,209,210,172,211,212,176],"system","json","text","system text json net11","policy","metadata","serialization","behavior","user","only","probe","guidance","later","type","dictionary","naming","targeting","custom","generic",{"skillNo":214,"name":215,"nameZh":6,"description":216,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":217,"categories":218,"keywords":221,"publishedAt":46},"01M6DZRRJP3S662NFSG1RSPQQ7","process-api-net11","Provides guidance on the new System.Diagnostics.Process APIs introduced in .NET 11: Process.Run, Process.RunAndCaptureText, Process.StartAndForget, Process.ReadAllText\u002FBytes\u002FLines, KillOnParentExit, InheritedHandles, and StartDetached. USE FOR: starting, orchestrating, or capturing output from external processes in applications targeting net11.0 or later. DO NOT USE FOR: applications targeting .NET 10 or earlier, or basic pre-.NET 11 Process.Start usage without new APIs.","https:\u002F\u002Fgithub.com\u002Fmanagedcode\u002Fdotnet-skills\u002Fblob\u002Fmain\u002Fexternal-sources\u002Fupstreams\u002Fdotnet-skills\u002Fplugins\u002Fdotnet11\u002Fskills\u002Fprocess-api-net11\u002FSKILL.md",[219,220],{"categoryNo":94,"categoryName":95,"taxonomyType":96,"taxonomyTypeDesc":97},{"categoryNo":99,"categoryName":100,"taxonomyType":101,"taxonomyTypeDesc":102},[111,222,223,224,107,225,160,194,37,205,206,36,226,227,228,229,210,172,22],"process","process api net11","diagnostics","start","basic","processes","output","usage"]