NodeJS 调用C++(Node-ffi)

网友投稿 1795 2022-11-25

Nodejs 调用C++(Node-ffi)

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}\0`, "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 #endif10 11 EXPORT int foo(int param) {12 int ret = param + 1;13 // do C++ things14 return ret;15 }16 17 EXPORT int bar() {18 int ret = 0;19 // do C++ things20 return ret;21 }22 23 #ifdef __cplusplus24 }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);

本文介绍如何用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}\0`, "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 #endif10 11 EXPORT int foo(int param) {12 int ret = param + 1;13 // do C++ things14 return ret;15 }16 17 EXPORT int bar() {18 int ret = 0;19 // do C++ things20 return ret;21 }22 23 #ifdef __cplusplus24 }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);

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:企业发票异常分析---查找作废次数
下一篇:动态添加按钮 TagCloudView
相关文章

 发表评论

暂时没有评论,来抢沙发吧~