Windows下Nodejs如何使用ffi-napi调用dll

步骤

  1. 编写add.c
#include   
  
__declspec(dllexport) int add(int a, int b) {  
    return a + b;  
}
  1. 使用gcc生成dll,这一步后生成add.dll

gcc -shared -o add.dll add.c -Wl,–out-implib,libadd.a
-Wl,–add-stdcall-alias是用于确保32位程序可以正确链接到64位DLL的GCC特定选项。如果你在64位机器上编译32位程序,或者反过来,你可能需要这个选项。

  1. 编写main.c,测试add.dll
#include   
#include   
  
__declspec(dllimport) int add(int a, int b);  
  
int main() {  
    int result = add(2, 3);  
    printf("The result is %d\n", result);  
    return 0;  
}
  1. 通过命令生成myprogram.exe。-ladd会链接上add.dll。

gcc -o myprogram myprogram.c -L. -ladd -Wl,–add-stdcall-alias

并测试myprogram.exe,输出

The result is 5

  1. 下载ffi-napi

npm install ffi-napi

  1. 创建main.js,编写代码
const ffi = require('ffi-napi');  
  
const myLib = ffi.Library('path/to/your/dll', {  
  'Add': ['int', ['int', 'int']],  
});  
  
// Now you can use myLib.Add(a, b) to call your DLL function.
const result = myLib.Add(1, 2);  
console.log(result); // Outputs: 3
  1. node main.js测试,测试结果

3

你可能感兴趣的:(Web,windows)