You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在其他.NET项目中使用C#生成且经Native AOT编译的DLL?

解决.NET 7 Native AOT原生DLL的调用问题

Native AOT编译生成的DLL是非托管原生二进制文件,并非标准.NET程序集,因此无法直接通过常规.NET项目引用的方式使用。以下是具体解决步骤:

1. 确保类库方法的正确导出

使用System.Runtime.InteropServices.ExportAttribute标记需要导出的静态方法,且方法参数、返回值必须是P/Invoke兼容的 blittable 类型(避免使用List、自定义类等.NET特有类型):

using System.Runtime.InteropServices;

public static class ExportedMethods
{
    [Export("AddNumbers")]
    public static int Add(int num1, int num2)
    {
        return num1 + num2;
    }

    [Export("GreetUser")]
    public static IntPtr Greet(string name)
    {
        // 字符串返回需用Marshal分配非托管内存,调用端需负责释放
        return Marshal.StringToHGlobalAnsi($"Hello, {name}!");
    }
}

2. 配置类库的Native AOT编译

修改类库项目文件(.csproj),启用Native AOT并指定目标平台:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <PublishAot>true</PublishAot>
    <RuntimeIdentifier>win-x64</RuntimeIdentifier> <!-- 根据实际平台选择,如linux-x64、osx-x64 -->
    <SelfContained>true</SelfContained>
  </PropertyGroup>
</Project>

执行发布命令生成原生DLL:

dotnet publish -c Release

3. 在调用项目中通过P/Invoke调用

调用端需使用[DllImport]声明非托管函数,而非ImportAttribute(后者用于COM互操作):

using System.Runtime.InteropServices;

class Program
{
    // 匹配导出的函数名和调用约定(Native AOT默认用Cdecl)
    [DllImport("YourAotLibrary.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
    private static extern int AddNumbers(int num1, int num2);

    [DllImport("YourAotLibrary.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
    private static extern IntPtr GreetUser(string name);

    static void Main()
    {
        // 调用简单数值方法
        int sum = AddNumbers(5, 3);
        Console.WriteLine($"Sum: {sum}");

        // 调用字符串返回方法,需手动释放非托管内存
        IntPtr greetPtr = GreetUser("Alice");
        string greetMsg = Marshal.PtrToStringAnsi(greetPtr);
        Console.WriteLine(greetMsg);
        Marshal.FreeHGlobal(greetPtr);
    }
}

4. 常见问题排查

  • 确认导出方法是静态的:非静态方法无法被Native AOT导出。
  • 检查平台一致性:调用项目的目标平台(x64/x86)必须与Native AOT编译的RuntimeIdentifier完全匹配。
  • 验证导出表:用工具查看DLL的导出函数,Windows下用dumpbin /exports YourAotLibrary.dll,Linux/macOS下用nm -D YourAotLibrary.so,确认目标函数已被正确导出。
  • 路径问题:将Native AOT生成的DLL复制到调用项目的输出目录,或在DllImport中指定完整路径。

内容的提问来源于stack exchange,提问作者LRetro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 11:33:02