在Electron中调用节点本机插件(C++)

use*_*077 7 c++ node.js electron

我是Node JS和Electron的新手.我正在尝试使用Electron和Node JS将C++与HTML集成.我已经通过一些例子给出了:GIT

我正在尝试做的是从我的网页的javascript中调用本机函数(hello()),这是由电子加载的.我已经习惯node-gyp configure了生成我的Visual Studio解决方案文件.(.sln).后来我用Visual Studio 2013 Express编译了我的代码,它在build\Release Folder中成功生成了我的.node文件.

这是我的index.js文件:

var addon = require('./build/Release/hello.node');
console.log(addon.hello());
Run Code Online (Sandbox Code Playgroud)

当我简单地运行它时node index.js,它给了我想要的输出:

world
Run Code Online (Sandbox Code Playgroud)

但是当我使用电子时问题就出现了.我正在使用电子二进制(32位)来运行我的网页.

以下是我的main.js文件:

var app = require('app');  // Module to control application life.
var BrowserWindow = require('browser-window');  // Module to create native browser window.


require('crash-reporter').start();

var mainWindow = null;

// Quit when all windows are closed.
app.on('window-all-closed', function() {
  if (process.platform != 'darwin') {
    app.quit();
  }
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
    mainWindow = new BrowserWindow({width: 1366, height: 768});
    mainWindow.loadUrl("file://" + __dirname + "/HtmlFile/index.html");
    mainWindow.on('closed', function() {
    mainWindow = null;
  });
});
Run Code Online (Sandbox Code Playgroud)

现在这是我的javascript,我在调用本机插件:

//************* My Functional logic **************
 //************************************************

var addon = require('../build/Release/hello');
alert(addon.hello());
Run Code Online (Sandbox Code Playgroud)

当我运行此或加载此页面时,我收到以下错误:

Uncaught Error: %1 is not a valid Win32 application. ATOM_SHELL_ASAR.js:137
C:\Users\Administrator\Desktop\MyAPP\build\Release\hello.node
Run Code Online (Sandbox Code Playgroud)

以下是我的package.json:

{
  "name": "MyAPP",
  "version": "1.0.0",
  "description": "Desc",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "nan": "^2.0.9"
  },
  "gypfile": true
}
Run Code Online (Sandbox Code Playgroud)

这是我的binding.gyp:

{
  "targets": [
    {
      "target_name": "hello",
      "sources": [ "hello.cc" ],
      "include_dirs": [
        "<!(node -e \"require('nan')\")"
      ]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*osh 2

看起来您可能没有配置正确的二进制文件。抱歉,不确定这是否适用于本机模块,但您可以尝试重建...

注意:请确保您的 node-gyp 命令具有正确的参数(如果这就是您将如何重建)。

  • --target=<your electron version>
  • --target_platform=win32(不在示例链接中,但您似乎使用的是 Windows)
  • --arch=<your architecture>(x64 = 64 位,x86 = 32 位)