N-API开发Node addons程序
参考:
依赖安装:npm install --global --production windows-build-tools
安装Yeoman:npm install -g yo
安装generator-napi-module:npm install -g generator-napi-module
创建示例项目:
mkdir hello-world
cd hello-world
yo napi-module
#include
#include
#include
using namespace Napi;
Napi::String Method(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
std::string name = (std::string)info[0].ToString();
HMODULE module = LoadLibrary("TestDll2.dll");
if (module == NULL) {
printf("加载dll失败");
return Napi::String::New(env, "fail");
}
typedef int(*AddFunc)(int, int);
AddFunc add = (AddFunc)GetProcAddress(module, "add");
int c = add(1, 2);
std::string d = std::to_string(c);
return Napi::String::New(env, "Hello " + name + d);
}
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "HellowWorld"),
Napi::Function::New(env, Method));
return exports;
}
NODE_API_MODULE(addon, Init)
初始化命令:node-gyp configure
编译命令:node-gyp rebuild
针对electron:
安装electron-rebuild:npm install --save-dev @electron/rebuild
针对electron编译(指定electron版本):electron-rebuild --version 13.0.0
electron项目配置
安装:npm install native-ext-loader@latest --save-dev
vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
pluginOptions: {
electronBuilder: {
nodeIntegration: true,
chainWebpackMainProcess(config) {
config.module
.rule("node")
.test(/\.node$/)
.use("native-ext-loader")
.loader("native-ext-loader")
},
chainWebpackRendererProcess: (config) => {
config.module
.rule("node")
.test(/\.node$/)
.use("native-ext-loader")
.loader("native-ext-loader")
.options({rewritePath:"src"})
},
builderOptions: {
/*
files:[
{
from: "src/main.node",
to: "src/",
}
],
*/
}
}
}
})
通过ipc交互
依赖的dll文件加载时,相对路径是electron项目的根目录