Electron调用C++

1
npm install --global --production windows-build-tools

引入

  1. node-gyp

    1
    npm install node-gyp -g
  2. window-build-tools

    1
    npm install windows-build-tools -g
  3. ffi-napi

    1
    npm install ffi-napi --save

封装

1
2
3
4
5
6
const ffi = require('ffi-napi')
const path = require('path')
const cppDemo = new ffi.Library(path.resolve(__dirname, 'resources/MyDLL'), {
'seekArea': ['double', ['int', 'int']]
})
module.exports = cppDemo;

C++动态链接库

  1. 新建C++项目(Windows桌面向导)

  2. 在头文件新建MyDLL.h

    1
    2
    3
    4
    5
    6
    7
    8
    #ifdef MYDLL_EXPORTS
    #define MYDLL_API __declspec(dllexport)
    #else
    #define MYDLL_API __declspec(dllimport)
    #endif

    extern "C" MYDLL_API double seekArea(int r, int h);

  3. 在源文件新建MyDLL.cpp

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    #include "stdio.h"
    #include "MyDLL.h"

    double area(int r) {
    return 3.14 * r * r;
    }

    MYDLL_API double seekArea(int r, int h) {
    double under = 3.14 * r * r;
    double v = under * h;
    return v;
    }

  4. 设置项目平台为x64,并设置解决方案生成方式为x64

  5. 生成DLL文件

参考文献

https://my.oschina.net/david1025/blog/3173842