electron 原生模块 addon 调用.dll文件例子

TestDLL.dll: 定义 DLL 应用程序的导出函数。

  #include "stdafx.h"

    extern "C" _declspec(dllexport) int Add(int x, int y)//申明函数为导出函数

    {

        int result = x + y;

        return result;

  }

addon.cc 文件编写实例

#define BUILDING_NODE_EXTENSION

#include <node.h>

#include <iostream>

#include <windows.h>

namespace demo {

using v8::Exception;

using v8::FunctionCallbackInfo;

using v8::Isolate;

using v8::Local;

using v8::NewStringType;

using v8::Number;

using v8::Object;

using v8::String;

using v8::Value;

// 这是 "add" 方法的实现。

// 输入参数使用 const FunctionCallbackInfo<Value>& args 结构传入。

void Add(const FunctionCallbackInfo<Value>& args) {

  Isolate* isolate = args.GetIsolate();

  // 检查传入的参数的个数。

    // if (args.Length() < 2) {

    //     isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate,"参数的数量错误",NewStringType::kNormal).ToLocalChecked()));

    //     return;

    // }

  // 检查参数的类型。

  // if (!args[0]->IsNumber() || !args[1]->IsNumber()) {

  //     isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate,"参数错误",NewStringType::kNormal).ToLocalChecked()));

  //     return;

// }

  typedef int(*DllAdd)(int, int);

  HINSTANCE hDll = LoadLibrary("TestDLL.dll");//加载DLL文件

  DllAdd dllAddFunc = (DllAdd)GetProcAddress(hDll, "Add");

  double value = dllAddFunc(args[0].As<Number>()->Value(), args[1].As<Number>()->Value());

  Local<Number> num = Number::New(isolate, value);

  FreeLibrary(hDll);

  // 执行操作

  // 设置返回值 (使用传入的 FunctionCallbackInfo<Value>&)。

  args.GetReturnValue().Set(num);

  }

void Init(Local<Object> exports) {

    // 相当于js的 module.exports=add,每个函数必有

    NODE_SET_METHOD(exports, "add", Add);

}

NODE_MODULE(NODE_GYP_MODULE_NAME, Init)

}  // 命名空间示例

cmd 执行以下操作:

-target=xxx electron的版本号

--arch=ia32: electron32位 --arch=x64 electron64位

  node-gyp configure --target=8.2.3 --arch=ia32 --dist-url=https://atom.io/download/atom-shell

  node-gyp build --target=8.2.3 --arch=ia32

出现以下信息即编译成功

已完成代码的生成

  add.vcxproj -> E:\code\addons\build\Release\\add.node

gyp info ok

// main.js 引入

const addons = require('./Release/add.node')

console.log(addons.add(1,2))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容