The electron function is very powerful, but there are some functions to interact with the bottom layer of the operating system, electron cannot be realized. In this case, we can call the native to complete the corresponding functions. This article mainly explains how to call C++ DLL files on the Windows platform

We’re going to install it before we start

1.node-gyp

npm install node-gyp -g
Copy the code

2.windows-build-tools

npm install windows-build-tools -g
Copy the code

The point to make here is that the Python version must be 2.7

Using ffi-napi to call DLL (c++)

1. Install the ffi – for a

perform

npm install ffi-napi --save
Copy the code

2. Prepare the C++ dynamic link library DLL file

Please go to Gitee to get the DLL file, there is no way to upload the electron- vie-demos

3. Invoke the method in the DLL file

const ffi = require('ffi-napi')
const path = require('path')
const Dll = ffi.Library(path.resolve('resources/dll/MyDLL.dll'), {
  Add: ['float'['float'.'float']],
  Hello: ['string'[]],StrLength: ['int'['string']]})Copy the code

This DLL provides a total of three methods,

  • The first method is to calculate the sum
  • The second method returns the string ‘Hello’
  • The third method is to calculate the length of the string

Concrete method call

callCppDll () {
      console.log('fii.Library Hello result:', Dll.Hello())
      console.log('fii.Library Add result:', Dll.Add(1.2))
      console.log('fii.Library Add result:', Dll.StrLength('hello world'))}Copy the code

Calling a DLL is simple, but requires the installation of node-gyp and C++ compilation tools. This article is based on the Windows platform for development, C++ compiled file is DLL, if on the Mac platform, need to compile C++ into dylib, next I come to a Mac platform

Please pay attention to the public account for more content