首页 > 网站 > 建站经验 > 正文

使用Node.js为其他_程序编写扩展的基本方法

2019-11-02 15:48:20
字体:
来源:转载
供稿:网友

   这篇文章主要介绍了使用Node.js为其他程序编写扩展的基本方法 ,文中示例是通过Node让JavaScript代码与C++应用产生交互,需要的朋友可以参考下

  准备开始

  首先我们用下面的目录结构来创建一个节点通知(node-notify)文件夹.

   代码如下:

  .

  |-- build/ # This is where our extension is built.

  |-- demo/

  | `-- demo.js # This is a demo Node.js script to test our extension.

  |-- src/

  | `-- node_gtknotify.cpp # This is the where we do the mapping from C++ to Javascript.

  `-- wscript # This is our build configuration used by node-waf

  这个看起来很漂亮的tree 用通用的 tree 生成.

  现在让我来创建测试脚本demo.js 和决定我们扩展的API前期看起来应该像:

  ?

  1

  2

  3

  4

  5

  6

  7

  8// This loads our extension on the notify variable.

  // It will only load a constructor function, notify.notification().

  var notify = require("../build/default/gtknotify.node"); // path to our extension

  var notification = new notify.notification();

  notification.title = "Notification title";

  notification.icon = "emblem-default"; // see /usr/share/icons/gnome/16x16

  notification.send("Notification message");

  编写我们的Node.js扩展

  Init方法

  为了创建一个Node.js扩展,我们需要编写一个继承node::ObjectWrap的C++类。 ObjectWrap 实现了让我们更容易与Javascript交互的公共方法

  我们先来编写类的基本框架:

  ?

  1

  2

  3

  4

  5

  6

  7

  8

  9

  10

  11

  12

  13

  14

  15

  16

  17

  18

  19

  20

  21

  22

  23

  24

  25

  26

  27

  28

  29

  30

  31

  32

  33

  34

  35

  36

  37#include // v8 is the Javascript engine used by QNode

  #include

  // We will need the following libraries for our GTK+ notification

  #include

  #include

  #include

  using namespace v8;

  class Gtknotify : node::ObjectWrap {

  private:

  public:

  Gtknotify() {}

  ~Gtknotify() {}

  static void Init(Handle target) {

  // This is what Node will call when we load the extension through require(), see boilerplate code below.

  }

  };

  /*

  * WARNING: Boilerplate code ahead.

  *

  * See https://www.cloudkick.com/blog/2010/aug/23/writing-nodejs-native-extensions/ & http://www.freebsd.org/cgi/man.cgi?query=dlsym

  *

  * Thats it for actual interfacing with v8, finally we need to let Node.js know how to dynamically load our code.

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表