NodeJS 调用C++(Node-ffi)

NodeJS 调用C++(Node-ffi)

 

本文介绍如何用Nodejsd调用C++代码

  • 用node-ffi实现

如果调用的C++ dll是32位接口,则NodeJS也需要确保是32位。

用ffi,则NodeJS必须是V10及以下的版本

NodeJS查看版本和位数:

node -v //查看版本号

node -p 'process' //在返回的arch和platform可以看详细信息

 

首先安装node-gyp(nodejs默认安装,若没有则用一下命令)

npm install -g node-gyp

安装ffi和ref 

npm install ffi

npm install ref

默认安装完会用node-gyp编译 

教程上说nodejs v11以上可以通过一下安装,但是我还是会报错。。。npm install @saleae/ffi

 

代码测试:

npm 调用windows Api:

复制代码
 1 var ffi = require('ffi');
 2 
 3 var c_txt = text => {
 4   return Buffer.from(`${text}`, "ucs2");
 5 };
 6 
 7 var current = ffi.Library("user32", {
 8   "MessageBoxW": ["int32", ["int32", "string", "string", "int32"]]
 9 });
10 
11 const ok_or_cancel = current.MessageBoxW(0, c_txt("Hello from NodeJs"), c_txt("node-ffi test"), 1);
12 
13 console.log(ok_or_cancel);
复制代码

新建一个C++ dll工程:

复制代码
 1 #if defined(WIN32) || defined(_WIN32)
 2 #define EXPORT __declspec(dllexport)
 3 #else
 4 #define EXPORT
 5 #endif
 6 
 7 #ifdef __cplusplus
 8 extern "C" {
 9 #endif
10 
11 EXPORT int foo(int param) {
12     int ret = param + 1;
13     // do C++ things
14     return ret;
15 }
16 
17 EXPORT int bar() {
18     int ret = 0;
19     // do C++ things
20     return ret;
21 }
22 
23 #ifdef __cplusplus
24 }
25 #endif
复制代码

NodeJS中调用:

复制代码
1 var basic = ffi.Library("./Project_dll_1", {
2   "foo": [ "int", ["int"] ],
3   "bar": [ "int", [] ]
4 })
5 
6 var v = basic.foo(1);
7 console.log(v);
复制代码

 

原文链接: https://www.cnblogs.com/onesea/p/15879880.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    NodeJS 调用C++(Node-ffi)

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/187802

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午1:47
下一篇 2023年2月12日 下午1:48

相关推荐