Electron 调用 C++ 插件 (.dll)

1、创建 dll

做一个简单的DLL,根据需要设置编译器位数。

这里创建了一个 ElectronDemoDLL.dll,用于接收并返回数据。

 

 2、创建 binding.gyp 和 ***.cpp

在 node_modules 目录下创建一个文件夹(如:ElectronDemoDll),并新建 binding.gyp 和 DemoDll.cpp。.cpp 的名字可以任意命名。

binding.gyp 内容如下:

{
  "targets": [
    {
      "target_name": "demodll",
      "sources": [ "DemoDll.cpp" ],
      "include_dirs": [
        "<!(node -e "require('nan')")"
      ]
    }
  ]
}

DemoDll.cpp 内容如下:

#include <nan.h>
#include <node.h>

void Method(const v8::FunctionCallbackInfo<v8::Value>& info) {
  v8::Isolate* isolate = info.GetIsolate();

  // 检查传入的参数的个数。
  if (info.Length() < 1) {
    // 抛出一个错误并传回到 JavaScript。
    isolate->ThrowException(
      v8::Exception::TypeError(
        v8::String::NewFromUtf8(isolate, "the number of para is wrong", v8::NewStringType::kNormal).ToLocalChecked()));
    return;
  }

  typedef bool(*DllAdd)(char*, char*);
  HINSTANCE hDll = LoadLibrary("ElectronDemoDLL.dll");    //  加载DLL文件
  DllAdd dllAddFunc = (DllAdd)GetProcAddress(hDll, "ShowMessage");
  
  //  v8 将javascript字符串转为char*
  v8::Local<v8::Value> arg = info[0];
  v8::Local<v8::String> ss = arg->ToString(); //  转为v8 的String类型
  v8::String::Utf8Value valueInput(ss); //  将v8::String类型转为 String::Utf8Value类型
  char* chInput = *valueInput;  //  String::Utf8Value类型转为char* 或者const char*
 
  char pOut[50];
  int result = 0;
  result = dllAddFunc(chInput, pOut);
  v8::Local<v8::String> value = v8::String::NewFromUtf8(isolate, pOut).ToLocalChecked();
  FreeLibrary(hDll);
  info.GetReturnValue().Set(value);
}

void Init(v8::Local<v8::Object> exports) {
  NODE_SET_METHOD(exports, "getmessage", Method);
}

NODE_MODULE(ElectronDemoDLL, Init)

3、到步骤2创建的目录下编译插件(这里是 ElectronDemoDll)

cd node_modules/ElectronDemoDll
node-gyp rebuild -target=6.0.2 -arch=x64 -dist-url=https://npm.taobao.org/mirrors/atom/

其中,6.0.2为 Electron 的版本号,x64 为插件编译的位数。编译成功后,会生成 build 文件夹

 在 build/Release/ 目录下会有一个 .node 文件,这个文件就是 Electron 识别的插件文件。

 4、调用插件

 结果如下:

 5、传参

在调用插件时,可以传入参数,并在 DemoDll.cpp 的方法中进行处理。

 6、遇到的问题

win32 error 126 Dll 文件的路径写错了,或者 Dll 有相关的依赖,依赖没有放在与入口 Dll 在同一级目录下。

win32 error 193 Dll 与当前的操作系统不匹配,当前系统是 64 位的 Dll 是 32 位的。

原文地址:https://www.cnblogs.com/zerotoinfinity/p/14183770.html