1. 程式人生 > 實用技巧 >Electron 呼叫 C++ 外掛 (.dll)

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