Electron 调用dll

本文介绍了如何在C#中使用electron12、Vue2和Node14开发环境中集成动态链库,包括使用electron-edge-js下载和管理库,处理dll路径问题,以及注意32位兼容性。着重讲述了npm包管理和可能出现的bug解决方法。
摘要由CSDN通过智能技术生成

1.开发问题: 使用C#的动态链库

2.开发环境: electron12 + vue2 + node14

{
    "electron": "^12.2.3",
    "vue": "^2.6.12",
    "node": "^14.21.3"
}
*electron版本控制好,不然会有很多bug

3.解决问题:

 1): npm 下载库  { "electron-edge-js": "^19.0.0" }

const edge = require('electron-edge-js');

//dll库的地址
const dll_url =  process.env.NODE_ENV == "development"
    ? "./resources/dll/xx.dll"               //开发路径
    : process.resourcesPath + '/dll/xx.dll'  //正式路径

//使用edge
const NationEcTrans = edge.func({
      assemblyFile: dll_url,//dll地址
      typeName: "Library1.Class1",// 类库名.类
      methodName: "test1"//方法名
    })

//如果没有 类库名.类 的话可能得重新写一个dll,去引入所需dll,按照下面示例

 2): 动态库dll实例

using System;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Text;

namespace Library1
{
    public class Class1
    {
        public async Task<object> test1(string str)
        {
            return "参数" + str;
        }
    }
}

*electron 32位才能调用32位dll

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
Electron 框架基于 Node.js 和 Chromium,可以使用 Node.js 的 `child_process` 模块来调用系统的 DLL 库。 首先,需要在 Electron 项目中安装 `ffi` 和 `ref` 两个 Node.js 模块,用于调用 DLL 库和处理数据类型。 然后,可以使用以下代码来调用 DLL 库: ```javascript const ffi = require('ffi'); const ref = require('ref'); const path = require('path'); // 定义 DLL 函数的参数类型和返回值类型 const intPtr = ref.refType('int'); const doublePtr = ref.refType('double'); const dll = ffi.Library(path.join(__dirname, 'example.dll'), { 'add': ['int', ['int', 'int']], 'multiply': ['double', ['double', 'double', doublePtr]], 'sort': ['void', [intPtr, 'int']] }); // 调用 DLL 函数 const result1 = dll.add(1, 2); console.log(result1); // 输出 3 const result2 = ref.alloc('double'); const result3 = dll.multiply(2.5, 3.5, result2); console.log(result3, result2.deref()); // 输出 8.75 8.75 const array = [3, 1, 4, 1, 5, 9]; const buffer = Buffer.alloc(array.length * ref.sizeof.int); array.forEach((value, index) => { buffer.writeInt32LE(value, index * ref.sizeof.int); }); dll.sort(buffer, array.length); console.log(buffer); // 输出 <Buffer 01 01 03 04 05 09> ``` 在上面的代码中,`ffi.Library` 函数用于加载 DLL 库,并定义 DLL 函数的参数类型和返回值类型。然后,可以使用 `dll` 对象调用 DLL 函数。注意,DLL 函数的参数和返回值类型需要与定义的类型一致,可以使用 `ref.refType` 定义指针类型,使用 `ref.alloc` 创建指针变量,使用 `deref` 方法获取指针指向的值。在调用 DLL 函数时,需要将 JavaScript 数组转换为 C 数组,可以使用 `Buffer.alloc` 创建缓冲区,使用 `writeInt32LE` 方法将数组元素写入缓冲区,然后将缓冲区的地址传递给 DLL 函数。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值