Skip to content

Plugin Development Tutorial zh

3cxc edited this page Oct 19, 2026 · 3 revisions

插件开发教程

本教程将指导您使用 NativePluginKit 为Unknown: Site-0 创建一个最小化插件


1. 创建项目

dotnet new classlib -n HelloWorldPlugin -f net9.0
cd HelloWorldPlugin

编辑 HelloWorldPlugin.csproj:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
  </PropertyGroup>

  <PropertyGroup>
    <PublishAot>true</PublishAot>
    <PublishRelease>true</PublishRelease>
    <PublishTrimmed>true</PublishTrimmed>
    <TrimMode>full</TrimMode>
    <NativeLib>Shared</NativeLib>
    <IlcExportUnmanagedEntrypoints>true</IlcExportUnmanagedEntrypoints>
    <IlcOptimizationPreference>Size</IlcOptimizationPreference>
  </PropertyGroup>

  <PropertyGroup>
    <IsPackable>false</IsPackable>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)' == 'Release'">
    <ControlFlowGuard>Guard</ControlFlowGuard>
    <IlcGenerateStackTraceData>false</IlcGenerateStackTraceData>
    <IlcGenerateCompleteTypeMetadata>false</IlcGenerateCompleteTypeMetadata>
    <IlcScanReflection>false</IlcScanReflection>
    <IlcDisableReflection>true</IlcDisableReflection>
    <IlcTrimMetadata>true</IlcTrimMetadata>
    <InvariantGlobalization>true</InvariantGlobalization>
    <MetadataUpdaterSupport>false</MetadataUpdaterSupport>
    <DebuggerSupport>false</DebuggerSupport>
    <DebugSymbols>false</DebugSymbols>
    <DebugType>none</DebugType>
    <StripSymbols>true</StripSymbols>
    <StackTraceSupport>true</StackTraceSupport>
    <TrimmerRemoveSymbols>true</TrimmerRemoveSymbols>
    <EventSourceSupport>false</EventSourceSupport>
    <MetricsSupport>false</MetricsSupport>
    <UseSystemResourceKeys>true</UseSystemResourceKeys>
    <HotReloadEnabled>false</HotReloadEnabled>
    <HttpActivityPropagationSupport>false</HttpActivityPropagationSupport>
    <XmlResolverIsNetworkingEnabledByDefault>false</XmlResolverIsNetworkingEnabledByDefault>
    <EnableUnsafeBinaryFormatterSerialization>false</EnableUnsafeBinaryFormatterSerialization>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="NativePluginKit" Version="3.0.0" />
    <UnmanagedEntryPointsAssembly Include="NativePluginKit" />
  </ItemGroup>

</Project>

2. 编写插件

创建 HelloWorldPlugin.cs:

using NativePluginKit.Features.Logging;
using NativePluginKit.Loader.Plugins;
using NativePluginKit.Loader.Plugins.Metadata;

namespace HelloWorldPlugin;

public partial class HelloWorldPlugin : Plugin, IPluginMetadata
{
    public static string Name        => "HelloWorldPlugin";
    public static string Description => "A simple hello world plugin.";
    public static string Author      => "Your Name";
    public static Version Version    => new(1, 0, 0);
    public static Version RequiredApiVersion => new(3, 0, 0);

    protected override void OnStart()
    {
        Log.PrintLog("Hello, World!");
    }

    public override void OnStop() { }
}

注意 — 类必须声明为 partial 并实现 IPluginMetadata, 源生成器会产出 GetPluginInfo、OnInit 和 OnStop 导出

元数据属性是静态的,因为它们在插件实例创建之前就会被读取


3. 使用宿主 API

日志

Log.PrintLog("普通信息");
Log.PrintWarning("警告信息");
Log.PrintError("错误信息");
Log.Debug("调试信息");

从插件调用时,日志会自动带插件名前缀,例如 [HelloWorldPlugin] 普通信息

枚举卡牌

using NativePluginKit.Features.Cards;

for (int i = 0; i < Card.GetCardCount(); i++)
{
    string name = Card.GetCardNameAt(i);
    Log.PrintLog($"{name}({Card.GetCardTypeEnum(name)})消耗 {Card.GetCost(name)}");
}

枚举实体

using NativePluginKit.Features.Entities;
using NativePluginKit.Features.Wrappers;

foreach (EntityId id in Entity.GetAllEntityIds())
{
    if (!Entity.Contains(id)) continue;
    Log.PrintLog($"{Entity.GetDisplayName(id)}:{Entity.GetCurrentHP(id)}/{Entity.GetMaxHP(id)}");
}

订阅事件

using NativePluginKit.Events;
using NativePluginKit.Features.Events;

EventBus.On<EntityDamagedEvent>((int)EventType.EntityDamaged, OnEntityDamaged);

private void OnEntityDamaged(EntityDamagedEvent e)
{
    var id = new EntityId(e.EntityId.Low, e.EntityId.High);
    Log.PrintLog($"{Entity.GetDisplayName(id)} 受到 {e.HpDamage} 点伤害");
}

访问原始 API 表

Warning

PluginContext.CurrentApi 可用但不推荐

Card, Entity, Log 等包装类已经封装了所有支持的操作,包括参数封送、签名缓存和 ABI 边界的 try/catch 保护,绕过它们意味着这些工作都要由你自己处理

HostApiTable api = Api;

4. 构建与部署

dotnet publish -c Release -r win-x64

将 bin/Release/net9.0/win-x64/publish/HelloWorldPlugin.dll 复制到主机的 <GameRoot>/plugins/ 目录:

<GameRoot>/
├── ExampleClient.exe
└── plugins/
    └── HelloWorldPlugin.dll

启动客户端,你将看到:

Loading plugin: HelloWorldPlugin v1.0.0.0 by 你的名字
你好,世界!

5. 生命周期

阶段 方法 说明
加载 GetPluginInfo 导出入口,首次调用时惰性构建并缓存 PluginInfo
加载 OnInit 导出入口,创建实例、注入 HostApiTable、调用 OnStart、注册 [MethodExport] 方法
启动 OnStart() 业务初始化
停止 OnStop 导出入口,调用插件实例的 OnStop() 方法,随后释放缓存的 PluginInfo

6. 注意事项

  • 不要从 OnStart / OnStop 抛出异常,它们无法穿越 ABI 边界,会被生成的存根捕获并返回默认值
  • 不要使用 Console.WriteLine,宿主看不到日志
  • 在 OnStop 中释放所有非托管资源,包括通过 EventBus.Off<T> 取消事件订阅
  • 每个程序集只能有一个类继承 Plugin,源生成器会为每个类生成入口点,同一程序集中的多个类会产生重复的符号导出

Table of contents

Getting Started


目录

快速开始

Clone this wiki locally