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 位的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM