electron、edge.js调用C#动态链接库的一些问题

16 阅读1分钟

Edge.js 是一个开源的互操作桥梁,它允许开发者在同一个进程中让 Node.js 和 .NET 代码一起运行。electron-edge-js在这个基础上对electron进行了适配,使得可以在electron中调用C#动态链路库。

1.安装electron-edge-js

npm install electron-edge-js

2.调用示例

需要注意的是dll在打包后文件路径会发生变化需要进行

/**
 * 调用 .NET DLL 中的方法
 * @param methodName - 方法名
 * @param params - 传递给 .NET 方法的参数(须可 JSON 序列化)
 * @param options - 可选配置:typeName,customSearchPaths(自定义 DLL 搜索路径)
 */
export async function callDotNetMethod(
  methodName: string,
  params?: any,
  options?: {
    typeName?: string;
    customSearchPaths?: string[];
  }
): Promise<any> {
  // 1. 定位 DLL
  const { dll, root } = locateDll(options?.customSearchPaths);
  process.env.DOTNET_ROOT = root;
  ensureEnvironment();
  // 2. 获取或创建方法代理
  const cacheKey = `${dll}|${options?.typeName || ''}|${methodName}`;
  let func = methodCache.get(cacheKey);
  if (!func) {
    func = edge.func({
      assemblyFile: dll,
      typeName: options?.typeName || '',
      methodName: methodName.trim(),
    });
    methodCache.set(cacheKey, func);
  }

  // 3. 执行调用
  return new Promise((resolve, reject) => {
    func(params, (error: any, result: any) => {
      if (error) {
        reject(error);
      } else {
        resolve(result);
      }
    });
  });
}

3.dll定位

  • 在打包后(例如使用 electron-builder 或 electron-forge),DLL 会被复制到 resources 目录下,因此需要根据 process.resourcesPath 动态构造路径。
  • 根据运行环境查找对应的路径