• NodeJS 调用C++(Nodeffi)


    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 #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);
    复制代码
  • 相关阅读:
    汇编指令lodsb和stosb、lodsd和stosd
    编码查询
    CLD汇编指令
    Win32编程
    MessageBox
    windows 数据类型
    STL总结
    解析结构化异常处理(SEH)(第二部分)
    FS[XX]
    ShellCode入门(提取ShellCode)
  • 原文地址:https://www.cnblogs.com/onesea/p/15879880.html
Copyright © 2020-2023  润新知