[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M76SGHVNBNVM1DMVDYTMAE5G":3,"skill-same:01M76SGHVNBNVM1DMVDYTMAE5G":56},{"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":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":14,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":30,"ownerDescription":6,"updatedAt":31,"install":32,"resources":45},"01M76SGHVNBNVM1DMVDYTMAE5G","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.","weiflycc-cmd\u002Fskills","weiflycc-cmd","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F250846518?v=4","01M756C4PFGZJWKK04WFB9S5XF","威飛工作室","01M756C4QJJ66QDXN2RN6SXY87",0,"MIT","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet\u002Fskills\u002Fdotnet-pinvoke\u002FSKILL.md",[],[],"2026-11-12 13:55:43",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` | `SetLastPInvokeError` |\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    SetLastPInvokeError = 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\n```csharp\n\u002F\u002F Win32 APIs — check SetLastError\n[LibraryImport(\"kernel32\", SetLastPInvokeError = 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 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\nNativeLibrary.SetDllImportResolver(typeof(MyLib).Assembly,\n    (name, assembly, searchPath) =>\n    {\n        if (name != \"mylib\") return IntPtr.Zero;\n        string libName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)\n            ? \"mylib.dll\"\n            : RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\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. Replace `SetLastError = true` with `SetLastPInvokeError = true`\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- [ ] `SetLastError`\u002F`SetLastPInvokeError` set for APIs that use OS error codes\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` | `SetLastPInvokeError` |\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    SetLastPInvokeError = 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\n```csharp\n\u002F\u002F Win32 APIs — check SetLastError\n[LibraryImport(\"kernel32\", SetLastPInvokeError = 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 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\nNativeLibrary.SetDllImportResolver(typeof(MyLib).Assembly,\n    (name, assembly, searchPath) =>\n    {\n        if (name != \"mylib\") return IntPtr.Zero;\n        string libName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)\n            ? \"mylib.dll\"\n            : RuntimeInformation.IsOSPlatform(OSPlatform.OSX)\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. Replace `SetLastError = true` with `SetLastPInvokeError = true`\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- [ ] `SetLastError`\u002F`SetLastPInvokeError` set for APIs that use OS error codes\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":24},"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","5810d492c9b301d8227f932bf87b5c954c4fa4d6","plugins\u002Fdotnet\u002Fskills\u002Fdotnet-pinvoke","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd","weiflycc.com","2026-11-10 03:26:55",{"source":8,"skillName":5,"commands":33,"prompt":43,"zipAvailable":44},[34,37,40],{"tool":35,"command":36},"npx","npx skills add weiflycc-cmd\u002Fskills --skill dotnet-pinvoke",{"tool":38,"command":39},"bunx","bunx skills add weiflycc-cmd\u002Fskills --skill dotnet-pinvoke",{"tool":41,"command":42},"pnpm","pnpm dlx skills add weiflycc-cmd\u002Fskills --skill dotnet-pinvoke","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet\u002Fskills\u002Fdotnet-pinvoke\u002FSKILL.md",true,[46,52],{"path":47,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":50,"sourceHtmlUrl":51},"references\u002Fdiagnostics.md","REFERENCE","参考文档",3732,"https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet\u002Fskills\u002Fdotnet-pinvoke\u002Freferences\u002Fdiagnostics.md",{"path":53,"resourceType":48,"resourceTypeDesc":49,"sizeBytes":54,"sourceHtmlUrl":55},"references\u002Ftype-mapping.md",3058,"https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet\u002Fskills\u002Fdotnet-pinvoke\u002Freferences\u002Ftype-mapping.md",[57,64,71,78,85,92],{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":19},"01M76SGT4WG5682JQJ0V3NSK6X","system-text-json-net11","Provides guidance on new System.Text.Json APIs introduced in .NET 11. It covers typed JsonTypeInfo access via GetTypeInfo\u003CT> and TryGetTypeInfo\u003CT> on JsonSerializerOptions, and the new JsonNamingPolicy.PascalCase static property. Use when serializing or deserializing JSON in .NET 11 applications and needing typed metadata access or PascalCase property naming.","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet11\u002Fskills\u002Fsystem-text-json-net11\u002FSKILL.md",[],[],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M76SGPNZYYV9BCZJW7BF7J8A","nuget-trusted-publishing","Set up NuGet trusted publishing (OIDC) on a GitHub Actions repo — replaces long-lived API keys with short-lived tokens. USE FOR: trusted publishing, NuGet OIDC, keyless NuGet publish, migrate from NuGet API key, NuGet\u002Flogin, secure NuGet publishing. DO NOT USE FOR: publishing to private feeds or Azure Artifacts (OIDC is nuget.org only). INVOKES: shell (powershell or bash), edit, create, ask_user for guided repo setup.","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet\u002Fskills\u002Fnuget-trusted-publishing\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M76SGDB9Z3GSB1CFW314NC84","csharp-scripts","Run file-based C# apps with the .NET CLI when the user explicitly wants C#\u002F.NET code without creating a project. Use for C# language\u002FAPI experiments, one-file C# apps, small multi-file C# apps composed with `#:include`\u002F`#:exclude`, or C# file-based apps linked with `#:ref`. Do not use for language-agnostic throwaway scripts, generic computations, Python\u002FPowerShell-style automation, full projects, or existing app integration.","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet\u002Fskills\u002Fcsharp-scripts\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":19},"01M76SG805T8W764WAKB1NP3CJ","thread-abort-migration","Guides migration of .NET Framework Thread.Abort usage to cooperative cancellation in modern .NET. USE FOR: modernizing code that calls Thread.Abort, catching ThreadAbortException, replacing Thread.ResetAbort, replacing Thread.Interrupt for thread termination, resolving PlatformNotSupportedException or SYSLIB0006 after retargeting to .NET 6+, migrating ASP.NET Response.End or Response.Redirect(url, true) which internally call Thread.Abort. DO NOT USE FOR: code that only uses Thread.Join, Thread.Sleep, or Thread.Start without any abort, interrupt, or ThreadAbortException usage — these APIs work identically in modern .NET and need no migration. Also not for projects staying on .NET Framework, or Thread.Abort usage inside third-party libraries you do not control.","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet-upgrade\u002Fskills\u002Fthread-abort-migration\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M76SG2588ZJBE5C51HYJJSKV","migrate-nullable-references","Enable nullable reference types in a C# project and systematically resolve all warnings. USE FOR: adopting NRTs in existing codebases, file-by-file or project-wide migration, fixing CS8602\u002FCS8618\u002FCS86xx warnings, annotating APIs for nullability, cleaning up null-forgiving operators, upgrading dependencies with new nullable annotations. DO NOT USE FOR: projects already fully migrated with zero warnings (unless auditing suppressions), fixing a handful of nullable warnings in code that already has NRTs enabled, suppressing warnings without fixing them, C# 7.3 or earlier projects. INVOKES: Get-NullableReadiness.ps1 scanner script.","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet-upgrade\u002Fskills\u002Fmigrate-nullable-references\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":19},"01M76SFTG3VZZ2BDS1J78074GX","migrate-dotnet9-to-dotnet10","Migrate a .NET 9 project or solution to .NET 10 and resolve all breaking changes. USE FOR: upgrading TargetFramework from net9.0 to net10.0, fixing build errors after updating the .NET 10 SDK, resolving source and behavioral changes in .NET 10 \u002F C# 14 \u002F ASP.NET Core 10 \u002F EF Core 10, updating Dockerfiles for Debian-to-Ubuntu base images, resolving obsoletion warnings (SYSLIB0058-SYSLIB0062), adapting to SDK\u002FNuGet changes (NU1510, PrunePackageReference), migrating System.Linq.Async to built-in AsyncEnumerable, fixing OpenApi v2 API changes, cryptography renames, and C# 14 compiler changes (field keyword, extension keyword, span overloads). DO NOT USE FOR: .NET Framework migrations, upgrading from .NET 8 or earlier (use migrate-dotnet8-to-dotnet9 first), greenfield .NET 10 projects, or cosmetic modernization. LOADS REFERENCES: csharp-compiler, core-libraries, sdk-msbuild (always); aspnet-core, efcore, cryptography, extensions-hosting, serialization-networking, winforms-wpf, containers-interop (selective).","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet-upgrade\u002Fskills\u002Fmigrate-dotnet9-to-dotnet10\u002FSKILL.md",[],[]]