Token导航 LogoToken导航

Agent Skill · 研究检索

dotnet-native-interop(dotnet 本机互操作)

dotnet-native-interop 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

dotnet-native-interop 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为操作浏览器;许可证信息还不明确,第三方扫描已通过,按安装量在研究检索类的 73,675 个 Skill 里排第 59,221。

总安装 392周安装 16GitHub Stars 15下载 127核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:dotnet-native-interop(dotnet 本机互操作)
来源仓库:https://github.com/wshaddix/dotnet-skills
仓库路径:skills/dotnet-native-interop
安装命令:
npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-native-interop
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-native-interop

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

用于查找、检索和筛选相关信息。dotnet-native-interop 属于研究检索类 Skill,可作为该场景下的辅助能力补充。适合根据关键词或场景快速定位候选结果。可结合来源仓库进一步核验具体用法。安装前建议确认权限范围与维护状态。注意:[LibraryImport] 需 .NET 7+ 支持。

来源仓库内路径:skills/dotnet-native-interop

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-native-i…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要操作浏览器,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

dotnet-native-interop 怎么安装?

在终端执行 npx skills add https://github.com/wshaddix/dotnet-skills --skill dotnet-native-interop。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

dotnet-native-interop 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

dotnet-native-interop 需要什么权限?

权限级别是操作浏览器。该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

dotnet-native-interop 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

dotnet-native-interop 用的人多吗?

公开数据是累计安装 392 次,近一周安装 16 次,下载 127 次,GitHub 15 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

dotnet-native-interop 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
dotnet-native-interop

dotnet 本机互操作 · 本页

39215操作浏览器未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

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

ScenarioUse
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 handle this.

Windows

Windows uses .dll files. The loader searches the application directory, system directories, and PATH.

// Windows library name includes .dll extension
[LibraryImport("sqlite3.dll")]
internal static partial int sqlite3_open(
    [MarshalAs(UnmanagedType.LPUTF8Str)] string filename,
    out nint db);

Windows also supports omitting the extension -- the loader appends .dll automatically:

[LibraryImport("sqlite3")]
internal static partial int sqlite3_open(
    [MarshalAs(UnmanagedType.LPUTF8Str)] string filename,
    out nint db);

macOS and Linux

macOS uses .dylib files; Linux uses .so files. The.NET runtime automatically probes common name variations (with and without lib prefix, with platform-specific extensions).

// Use the logical name without extension -- .NET probes:
// libsqlite3.dylib (macOS), libsqlite3.so (Linux), sqlite3.dll (Windows)
[LibraryImport("libsqlite3")]
internal static partial int sqlite3_open(
    [MarshalAs(UnmanagedType.LPUTF8Str)] string filename,
    out nint db);

.NET probing order for library name "foo":

  1. foo (exact name)
  2. foo.dll, foo.so, foo.dylib (platform extension)
  3. libfoo, libfoo.so, libfoo.dylib (lib prefix + extension)

iOS

iOS does not allow loading dynamic libraries at runtime. Native code must be statically linked into the application binary. Use __Internal as the library name to call functions linked into the main executable:

// Calls a function statically linked into the iOS app binary
[LibraryImport("__Internal")]
internal static partial int NativeFunction(int input);

For iOS, the native library must be compiled as a static library (.a) and linked during the Xcode build phase. MAUI and Xamarin handle this through native references in the project file:

<ItemGroup Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'ios'">
  <NativeReference Include="libs/libmynative.a">
    <Kind>Static</Kind>
    <ForceLoad>true</ForceLoad>
  </NativeReference>
</ItemGroup>

Android

Android uses .so files loaded from the app's native library directory. The library name typically omits the lib prefix and .so extension in the P/Invoke declaration:

// Android loads libmynative.so from the APK's lib/<abi>/ directory
[LibraryImport("mynative")]
internal static partial int NativeFunction(int input);

Include platform-specific .so files for each target ABI in the project:

<ItemGroup Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">
  <AndroidNativeLibrary Include="libs/arm64-v8a/libmynative.so" Abi="arm64-v8a" />
  <AndroidNativeLibrary Include="libs/x86_64/libmynative.so" Abi="x86_64" />
</ItemGroup>

WASM

WebAssembly does not support traditional P/Invoke. Native C/C++ code cannot be called via [LibraryImport] or [DllImport] in browser WASM. For JavaScript interop, see [skill:dotnet-aot-wasm].


NativeLibrary.SetDllImportResolver

NativeLibrary.SetDllImportResolver (.NET Core 3.0+) provides runtime control over library resolution. This is the recommended approach for cross-platform library loading when static name probing is insufficient.

using System.Reflection;
using System.Runtime.InteropServices;

// Register once at startup (per assembly)
NativeLibrary.SetDllImportResolver(
    Assembly.GetExecutingAssembly(),
    DllImportResolver);

static nint DllImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
{
    if (libraryName == "mynativelib")
    {
        if (OperatingSystem.IsWindows())
            return NativeLibrary.Load("mynative.dll", assembly, searchPath);

        if (OperatingSystem.IsMacOS())
            return NativeLibrary.Load("libmynative.dylib", assembly, searchPath);

        if (OperatingSystem.IsLinux())
            return NativeLibrary.Load("libmynative.so.1", assembly, searchPath);
    }

    // Fall back to default resolution
    return nint.Zero;
}

Common Use Cases for DllImportResolver

ScenarioWhy resolver is needed
Versioned .so on Linux (e.g., libfoo.so.2)Default probing does not check versioned names
Library in a non-standard pathLoad from a custom directory at runtime
Bundled native library per RIDResolve to runtimes/<rid>/native/ path
Feature detection at load timeTry multiple library names and fall back gracefully

NativeLibrary API

The NativeLibrary class provides low-level library management:

// Load a library explicitly
nint handle = NativeLibrary.Load("mylib");

// Try to load without throwing
if (NativeLibrary.TryLoad("mylib", out nint h))
{
    // Get a function pointer by name
    nint funcPtr = NativeLibrary.GetExport(h, "my_function");

    // Or try without throwing
    if (NativeLibrary.TryGetExport(h, "my_function", out nint fp))
    {
        // Use function pointer
    }

    NativeLibrary.Free(h);
}

Marshalling Patterns

Struct Marshalling

Structs passed to native code must have a well-defined memory layout. Use [StructLayout] to control layout and alignment.

using System.Runtime.InteropServices;

// Sequential layout -- fields laid out in declaration order
[StructLayout(LayoutKind.Sequential)]
public struct Point
{
    public int X;
    public int Y;
}

// Explicit layout -- fields at specific byte offsets (for unions)
[StructLayout(LayoutKind.Explicit)]
public struct ValueUnion
{
    [FieldOffset(0)] public int IntValue;
    [FieldOffset(0)] public float FloatValue;
    [FieldOffset(0)] public double DoubleValue;
}

// Sequential with packing -- override default alignment
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct PackedHeader
{
    public byte Magic;
    public int Length;     // No padding before this field
    public short Version;
}

Blittable structs (containing only primitive value types with sequential/explicit layout) are passed directly to native code without copying. Non-blittable structs require marshalling, which incurs overhead.

Blittable primitive types: byte, sbyte, short, ushort, int, uint, long, ulong, float, double, nint, nuint.

Not blittable: bool (marshals as 4-byte BOOL by default), char (depends on charset), string, arrays of non-blittable types.

String Marshalling

Specify string encoding explicitly. Never rely on default marshalling behavior.

// UTF-8 strings (most common for cross-platform C APIs)
[LibraryImport("mylib", StringMarshalling = StringMarshalling.Utf8)]
internal static partial int ProcessText(string input);

// UTF-16 strings (Windows APIs)
[LibraryImport("mylib", StringMarshalling = StringMarshalling.Utf16)]
internal static partial int ProcessTextW(string input);

// Per-parameter marshalling when methods mix encodings
[LibraryImport("mylib")]
internal static partial int MixedApi(
    [MarshalAs(UnmanagedType.LPUTF8Str)] string utf8Param,
    [MarshalAs(UnmanagedType.LPWStr)] string utf16Param);

For output string buffers, use char[] or byte[] from ArrayPool instead of StringBuilder:

[LibraryImport("mylib")]
internal static partial int GetName(
    [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] char[] buffer,
    int bufferSize);

// Usage
char[] buffer = ArrayPool<char>.Shared.Rent(256);
try
{
    int result = GetName(buffer, buffer.Length);
    string name = new string(buffer, 0, result);
}
finally
{
    ArrayPool<char>.Shared.Return(buffer);
}

Function Pointer Callbacks

Modern.NET (.NET 5+) prefers unmanaged function pointers over delegate-based callbacks for better performance and AOT compatibility.

Preferred: Unmanaged function pointers with [UnmanagedCallersOnly]

using System.Runtime.InteropServices;

// Native callback signature: int (*callback)(int value, void* context)
[LibraryImport("mylib")]
internal static unsafe partial void RegisterCallback(
    delegate* unmanaged[Cdecl]<int, nint, int> callback,
    nint context);

// Callback implementation
[UnmanagedCallersOnly(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
static int MyCallback(int value, nint context)
{
    // Process value
    return 0;
}

// Registration
unsafe
{
    RegisterCallback(&MyCallback, nint.Zero);
}

Alternative: Delegate-based callbacks (when managed state is needed)

// Define delegate matching native signature
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate int NativeCallback(int value, nint context);

[LibraryImport("mylib")]
internal static partial void RegisterCallbackDelegate(
    NativeCallback callback,
    nint context);

// Usage -- prevent GC collection during native use
static NativeCallback? s_callback;

static void Setup()
{
    s_callback = new NativeCallback(MyManagedCallback);
    RegisterCallbackDelegate(s_callback, nint.Zero);
    // Keep s_callback alive as long as native code may call it
}

static int MyManagedCallback(int value, nint context)
{
    return value * 2;
}

SafeHandle for Resource Lifetime

Use SafeHandle subclasses to manage native resource lifetimes instead of raw IntPtr/nint. This prevents resource leaks and use-after-free bugs.

using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;

// Custom SafeHandle for a native resource
public class NativeResourceHandle : SafeHandleZeroOrMinusOneIsInvalid
{
    private NativeResourceHandle() : base(ownsHandle: true) { }

    protected override bool ReleaseHandle()
    {
        NativeApi.CloseResource(handle);
        return true;
    }
}

public static partial class NativeApi
{
    [LibraryImport("mylib")]
    internal static partial NativeResourceHandle OpenResource(
        [MarshalAs(UnmanagedType.LPUTF8Str)] string name);

    [LibraryImport("mylib")]
    internal static partial void CloseResource(nint handle);

    [LibraryImport("mylib")]
    internal static partial int ReadResource(NativeResourceHandle handle,
        Span<byte> buffer, int count);
}

Cross-Platform Data Type Mapping

Map C/C++ types to.NET types carefully. Some C types have platform-dependent sizes.

Fixed-Size Types

C/C++ Type.NET TypeSize
int8_t / charsbyte1 byte
uint8_t / unsigned charbyte1 byte
int16_t / shortshort2 bytes
uint16_t / unsigned shortushort2 bytes
int32_t / intint4 bytes
uint32_t / unsigned intuint4 bytes
int64_t / long longlong8 bytes
uint64_t / unsigned long longulong8 bytes
floatfloat4 bytes
doubledouble8 bytes

Platform-Dependent Types

C/C++ Type.NET TypeNotes
size_t / ptrdiff_tnint / nuintPointer-sized
void* / pointer typesnint or void*Pointer-sized
long (C/C++)CLong (.NET 6+)4 bytes on Windows, 8 bytes on Unix 64-bit
unsigned longCULong (.NET 6+)Same platform variance as long
Windows BOOLint4 bytes (not bool)
Windows BOOLEANbyte1 byte

Do not use C# long for C/C++ long -- they have different sizes on Unix 64-bit. Use CLong/CULong for portable interop.


Agent Gotchas

  1. Do not use [DllImport] in new.NET 7+ code without justification. Use [LibraryImport] which generates marshalling at compile time. Only fall back to [DllImport] when SYSLIB1054 analyzer indicates incompatibility.
  2. Do not assume bool marshals as 1 byte..NET marshals bool as a 4-byte Windows BOOL by default. Use [MarshalAs(UnmanagedType.U1)] for C _Bool/bool, or [MarshalAs(UnmanagedType.Bool)] for Windows BOOL explicitly.
  3. Do not use C# long to interop with C/C++ long. C long is 4 bytes on Windows but 8 bytes on 64-bit Unix. Use CLong/CULong (.NET 6+) for cross-platform correctness.
  4. Do not use StringBuilder for output string buffers. [LibraryImport] does not support StringBuilder at all, and with [DllImport] it allocates multiple intermediate copies. Use char[] or byte[] from ArrayPool instead.
  5. Do not use [LibraryImport] or [DllImport] for WASM. WebAssembly does not support traditional P/Invoke. For JavaScript interop in WASM, see [skill:dotnet-aot-wasm].
  6. Do not use dynamic library loading on iOS. iOS prohibits loading dynamic libraries at runtime. Use "__Internal" as the library name for statically linked native code.
  7. Do not use System.Delegate fields in interop structs. Use typed delegates or unmanaged function pointers (delegate* unmanaged). Untyped delegates can destabilize the runtime during marshalling.
  8. Do not forget to keep delegate instances alive during native use. The GC may collect a delegate that native code still references. Store delegates in a static field or use GCHandle for the duration of native callbacks.

Prerequisites

  • .NET 7+ SDK for [LibraryImport] source generation
  • .NET Core 3.0+ for NativeLibrary API
  • Native libraries compiled for each target platform/architecture
  • For iOS: Xcode with native static libraries linked via NativeReference
  • For Android: native .so files for each target ABI (arm64-v8a, x86_64)

References

平台分布

Codex

36.89%
按下载量换算47

Claude

28.61%
按下载量换算36

Cursor

19.1%
按下载量换算24

Gemini CLI

10.81%
按下载量换算14

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

操作浏览器

该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills