BlueRoseNote/07-Other/Node.js/在Node.js中使用ffi调用dll.md
2023-06-29 11:55:02 +08:00

55 lines
1.8 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

> 类似的文章还是比较多的,但或多或少有一些问题没有解决,在此我将其整合并分享给大家:
## 测试环境:
- Node.js 9.9.0
- VisualStudio 2015
- "ffi": "gavignus/node-ffi#torycl/forceset-fix",
- "ref": "1.3.5"
- "ref-array": "1.2.0"
- "ref-struct": "1.1.0"
- "ffi-napi": "^2.4.3"
## 编译失败:
当前情况下编译ffi会失败所以有两种解决方法
1. 使用新的ffi-napiapi是一样的同时支持node.js新的napi
2. 使用第三方修改过的ffi在package.json中将ffi后面的版本号改成
> "ffi": "gavignus/node-ffi#torycl/forceset-fix"
## 使用:
```
var ffi = require('ffi');
//第一个形参为dll所在位置dll文件可以不用加.dll第二个为函数信息
var libm = ffi.Library(__dirname + 'dllFile', {
//函数名
'fun': ['int', ['string', 'string']]
});
//调用
var str1="a";
var str2="b";
libm.fun(str1, str2);
```
## 使用c++里的类型
ref、ref-struct、ref-array、ref-union、ref-wchar
在npm查看使用方法在此不做赘述。
## 运行时遇到的错误
1. c++代码是可以用的但是需要把代码写在extern "C"{}里,不过这个我没有亲自试过。
2. dll文件需要放到node.js 执行目录,也就是
```
//即x:\xxxxx\xx
cd /d x:\xxxxx\xx;
node xxx.js;
```
3. dll如果有互相依赖的必须放全。不然只会出现错误126而不会像一般程序那样提示缺少xxx.dll。所以报错了可以用depends看一下dll全了没。
4. dll的需要与node.js的平台相对应比如你的node.js是64位版本的那你的dll也需要使用64位编译。
错误126检查上述1、2、3步。
## 参考:
- wiki
- https://github.com/node-ffi/node-ffi/wiki/Node-FFI-Tutorial<br>
- https://www.jianshu.com/p/914103283ea0
- https://blog.csdn.net/zhulin2609/article/details/51474676