Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

dotnet-native-interop

БесплатноБез исполняемых скриптовНе проверен

Calling native libraries via P/Invoke. LibraryImport, marshalling, cross-platform resolution.

wshaddixот wshaddix★ 94 звезды на GitHub

Об этом скилле

dotnet-native-interop

Platform Invoke (P/Invoke) patterns for calling native C/C++ libraries from .NET: [LibraryImport] (preferred, .NET 7+) vs [DllImport] (legacy), struct marshalling, string marshalling, function pointer callbacks, NativeLibrary.SetDllImportResolver for cross-platform library resolution, and platform-specific considerations for Windows, macOS, Linux, iOS, and Android.

Version assumptions: .NET 7.0+ baseline for [LibraryImport]. [DllImport] available in all .NET versions. NativeLibrary API available since .NET Core 3.0.

Scope boundary: This skill owns general P/Invoke guidance -- declaring native method signatures, marshalling data types, resolving library paths across platforms, and callback patterns. AOT-specific P/Invoke concerns (direct pinvoke, compile-time marshalling for AOT publishing) are in [skill:dotnet-native-aot]. Windows COM interop and CsWin32 source generator usage are in [skill:dotnet-winui]. WASM has no traditional P/Invoke support -- see [skill:dotnet-aot-wasm] for JavaScript interop via [JSImport]/[JSExport].

Out of scope: COM interop (Windows legacy). CsWin32 source generator -- see [skill:dotnet-winui]. JNI bridge for Android Java interop (different mechanism from P/Invoke). [JSImport]/[JSExport] for WASM -- see [skill:dotnet-aot-wasm].

Cross-references: [skill:dotnet-native-aot] for AOT-specific P/Invoke and [LibraryImport] in publish scenarios, [skill:dotnet-aot-architecture] for AOT-first design patterns including source-generated interop, [skill:dotnet-winui] for CsWin32 source generator and COM interop, [skill:dotnet-aot-wasm] for WASM JavaScript interop (not native P/Invoke).


LibraryImport vs DllImport

[LibraryImport] (.NET 7+) is the preferred attribute for new P/Invoke declarations. It uses source generation to produce marshalling code at compile time, making it fully AOT-compatible and eliminating runtime codegen overhead.

[DllImport] is the legacy attribute. It relies on runtime marshalling, which may require codegen not available in AOT scenarios. Use [DllImport] only when targeting .NET 6 or earlier, or when the SYSLIB1054 analyzer indicates [LibraryImport] cannot handle a specific signature.

Decision Guide

Scenario Use
New code targeting .NET 7+ [LibraryImport]
Targeting .NET 6 or earlier [DllImport]
SYSLIB1054 analyzer flags incompatibility [DllImport] (with comment explaining why)
Publishing with Native AOT [LibraryImport] (required for full AOT compat)

LibraryImport Declaration

using System.Runtime.InteropServices;

public static partial class NativeApi
{
    [LibraryImport("mylib")]
    internal static partial int ProcessData(
        ReadOnlySpan<byte> input,
        int length);

    [LibraryImport("mylib", StringMarshalling = StringMarshalling.Utf8)]
    internal static partial int OpenByName(string name);

    [LibraryImport("mylib", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static partial bool CloseResource(nint handle);
}

Key requirements for [LibraryImport]:

  • Method must be static partial in a partial class
  • String marshalling must be explicitly specified via StringMarshalling or [MarshalAs] on each string parameter (only needed when strings are present)
  • Boolean return types require explicit [return: MarshalAs(UnmanagedType.Bool)]
  • Span<T> and ReadOnlySpan<T> parameters are supported directly -- [DllImport] does not support them (use arrays instead)

DllImport Declaration (Legacy)

using System.Runtime.InteropServices;

public static class NativeApiLegacy
{
    [DllImport("mylib", CharSet = CharSet.Unicode, SetLastError = true)]
    internal static extern int ProcessData(
        byte[] input,
        int length);

    [DllImport("mylib", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool CloseResource(IntPtr handle);
}

Migrating DllImport to LibraryImport

The SYSLIB1054 analyzer suggests converting [DllImport] to [LibraryImport] and provides code fixes. Key changes:

  1. Replace [DllImport] with [LibraryImport]
  2. Change static extern to static partial
  3. Make the containing class partial
  4. Replace CharSet with StringMarshalling
  5. Replace IntPtr with nint where appropriate
  6. Add explicit [MarshalAs] for bool parameters and returns
// Before (DllImport)
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
static extern IntPtr LoadLibrary(string lpLibFileName);

// After (LibraryImport)
[LibraryImport("kernel32.dll", StringMarshalling = StringMarshalling.Utf16,
    SetLastError = true)]
internal static partial nint LoadLibrary(string lpLibFileName);

Platform-Specific Library Names

Native library names differ across platforms. Use NativeLibrary.SetDllImportResolver or conditional compilation to han

Полный SKILL.md на GitHub

Установить dotnet-native-interop в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл dotnet-native-interop?

Calling native libraries via P/Invoke. LibraryImport, marshalling, cross-platform resolution.

Как установить скилл dotnet-native-interop?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл dotnet-native-interop запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить dotnet-native-interop с