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

如何在C# WebAssembly中加载本地DLL?运行报错求助

C# WebAssembly中使用DllImport加载本地DLL失败的解决方案

问题本质

WebAssembly运行在浏览器沙箱环境中,无法直接访问本地操作系统的原生DLL(比如Windows平台的enet.dll)。DllImport在WASM场景下仅支持调用编译为WebAssembly格式的原生模块(.wasm文件),而非桌面系统的动态链接库。

解决步骤

  1. 编译WASM版本的ENet库
    你需要将ENet的C/C++源码通过Emscripten工具链编译为WebAssembly格式的.wasm文件,而非使用Windows平台的enet.dll。编译时需确保导出目标函数,例如用Emscripten编译时添加参数:

    emcc enet.c -o enet.wasm -s EXPORTED_FUNCTIONS=['_enet_initialize'] -s ALLOW_MEMORY_GROWTH=1
    
  2. 配置项目依赖

    • 将编译好的enet.wasm文件添加到Blazor WASM项目中,右键设置文件属性为「复制到输出目录:始终复制」。
    • 修改DllImport的配置,适配WASM模块:
      using System;
      using System.Runtime.InteropServices.JavaScript;
      using System.Runtime.InteropServices;
      
      public partial class MyClass
      {
          // 注意模块名是不带.wasm后缀的文件名,指定调用约定为Cdecl
          [DllImport("enet", EntryPoint = "_enet_initialize", CallingConvention = CallingConvention.Cdecl)]
          public static extern int enet_initialize();
      
          [JSExport]
          internal static void Test()
          {
              try
              {
                  Console.WriteLine("ENET: " + enet_initialize());
              }
              catch (Exception ex)
              {
                  Console.WriteLine($"调用失败: {ex.Message}");
              }
          }
      }
      
    • 在项目的.csproj文件中添加原生文件引用,确保模块被正确打包:
      <ItemGroup>
        <NativeFileReference Include="enet.wasm" />
      </ItemGroup>
      
  3. 调试与验证

    • 打开浏览器开发者工具的「Console」标签页,查看更详细的错误日志(当前给出的错误信息过于简略,无法定位具体问题)。
    • 确认WASM模块中的函数名称与EntryPoint参数一致(Emscripten编译后函数名会自动添加下划线前缀,比如enet_initialize会变成_enet_initialize)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 06:13:33