当前位置: 首页 > 工具软件 > Behave.js > 使用案例 >

Node.js v12.16.2 Documentation C++ Addons

孙永思
2023-12-01
Index View on single page View as JSON View another version ▼ 

Edit on GitHub 

Table of Contents

C++ Addons

    Hello world

        Context-aware addons
            Worker support
        Building
        Linking to libraries included with Node.js
        Loading Addons using require()
    Native Abstractions for Node.js
    N-API

    Addon examples
        Function arguments
        Callbacks
        Object factory
        Function factory
        Wrapping C++ objects
        Factory of wrapped objects
        Passing wrapped objects around

C++ Addons

Addons are dynamically-linked shared objects written in C++. The require() function can load Addons as ordinary Node.js modules. Addons provide an interface between JavaScript and C/C++ libraries.

There are three options for implementing Addons: N-API, nan, or direct use of internal V8, libuv and Node.js libraries. Unless you need direct access to functionality which is not exposed by N-API, use N-API. Refer to C/C++ Addons with N-API for more information on N-API.

When not using N-API, implementing Addons is complicated, involving knowledge of several components and APIs:

V8: the C++ library Node.js currently uses to provide the JavaScript implementation. V8 provides the mechanisms for creating objects, calling functions, etc. V8's API is documented mostly in the v8.h header file (deps/v8/include/v8.h in the Node.js source tree), which is also available online.

libuv: The C library that implements the Node.js event loop, its worker threads and all of the asynchronous behaviors of the platform. It also serves as a cross-platform abstraction library, giving easy, POSIX-like access across all major operating systems to many common system tasks, such as interacting with the filesystem, sockets, timers, and system events. libuv also provides a pthreads-like threading abstraction that may be used to power more sophisticated asynchronous Addons that need to move beyond the standard event loop. Addon authors are encouraged to think about how to avoid blocking the event loop with I/O or other time-intensive tasks by off-loading work via libuv to non-blocking system operations, worker threads or a custom use of libuv's threads.

Internal Node.js libraries. Node.js itself exports C++ APIs that Addons can use, the most important of which is the node::ObjectWrap class.

Node.js includes other statically linked libraries including OpenSSL. These other libraries are located in the deps/ directory in the Node.js source tree. Only the libuv, OpenSSL, V8 and zlib symbols are purposefully re-exported by Node.js and may be used to various extents by Addons. See Linking to libraries included with Node.js for additional information.

All of the following examples are available for download and may be used as the starting-point for an Addon.
Hello world

This “Hello world” example is a simple Addon, written in C++, that is the equivalent of the following JavaScript code:

module.exports.hello = () => ‘world’;

First, create the file hello.cc:

// hello.cc
#include <node.h>

namespace demo {

using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::NewStringType;
using v8::Object;
using v8::String;
using v8::Value;

void Method(const FunctionCallbackInfo& args) {
Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set(String::NewFromUtf8(
isolate, “world”, NewStringType::kNormal).ToLocalChecked());
}

void Initialize(Local exports) {
NODE_SET_METHOD(exports, “hello”, Method);
}

NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)

} // namespace demo

All Node.js Addons must export an initialization function following the pattern:

void Initialize(Local exports);
NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)

There is no semi-colon after NODE_MODULE as it’s not a function (see node.h).

The module_name must match the filename of the final binary (excluding the .node suffix).

In the hello.cc example, then, the initialization function is Initialize and the addon module name is addon.

When building addons with node-gyp, using the macro NODE_GYP_MODULE_NAME as the first parameter of NODE_MODULE() will ensure that the name of the final binary will be passed to NODE_MODULE().
Context-aware addons

There are environments in which Node.js addons may need to be loaded multiple times in multiple contexts. For example, the Electron runtime runs multiple instances of Node.js in a single process. Each instance will have its own require() cache, and thus each instance will need a native addon to behave correctly when loaded via require(). From the addon’s perspective, this means that it must support multiple initializations.

A context-aware addon can be constructed by using the macro NODE_MODULE_INITIALIZER, which expands to the name of a function which Node.js will expect to find when it loads an addon. An addon can thus be initialized as in the following example:

using namespace v8;

extern “C” NODE_MODULE_EXPORT void
NODE_MODULE_INITIALIZER(Local exports,
Local module,
Local context) {
/* Perform addon initialization steps here. */
}

Another option is to use the macro NODE_MODULE_INIT(), which will also construct a context-aware addon. Unlike NODE_MODULE(), which is used to construct an addon around a given addon initializer function, NODE_MODULE_INIT() serves as the declaration of such an initializer to be followed by a function body.

The following three variables may be used inside the function body following an invocation of NODE_MODULE_INIT():

Local<Object> exports,
Local<Value> module, and
Local<Context> context

The choice to build a context-aware addon carries with it the responsibility of carefully managing global static data. Since the addon may be loaded multiple times, potentially even from different threads, any global static data stored in the addon must be properly protected, and must not contain any persistent references to JavaScript objects. The reason for this is that JavaScript objects are only valid in one context, and will likely cause a crash when accessed from the wrong context or from a different thread than the one on which they were created.

The context-aware addon can be structured to avoid global static data by performing the following steps:

defining a class which will hold per-addon-instance data. Such a class should include a v8::Global<v8::Object> which will hold a weak reference to the addon's exports object. The callback associated with the weak reference will then destroy the instance of the class.
constructing an instance of this class in the addon initializer such that the v8::Global<v8::Object> is set to the exports object.
storing the instance of the class in a v8::External, and
passing the v8::External to all methods exposed to JavaScript by passing it to the v8::FunctionTemplate constructor which creates the native-backed JavaScript functions. The v8::FunctionTemplate constructor's third parameter accepts the v8::External.

This will ensure that the per-addon-instance data reaches each binding that can be called from JavaScript. The per-addon-instance data must also be passed into any asynchronous callbacks the addon may create.

The following example illustrates the implementation of a context-aware addon:

#include <node.h>

using namespace v8;

class AddonData {
public:
AddonData(Isolate* isolate, Local exports):
call_count(0) {
// Link the existence of this object instance to the existence of exports.
exports_.Reset(isolate, exports);
exports_.SetWeak(this, DeleteMe, WeakCallbackType::kParameter);
}

// Per-addon data.
int call_count;

private:
// Method to call when “exports” is about to be garbage-collected.
static void DeleteMe(const WeakCallbackInfo& info) {
delete info.GetParameter();
}

// Weak handle to the “exports” object. An instance of this class will be
// destroyed along with the exports object to which it is weakly bound.
v8::Globalv8::Object exports_;
};

static void Method(const v8::FunctionCallbackInfov8::Value& info) {
// Retrieve the per-addon-instance data.
AddonData* data =
reinterpret_cast<AddonData*>(info.Data().As()->Value());
data->call_count++;
info.GetReturnValue().Set((double)data->call_count);
}

// Initialize this addon to be context-aware.
NODE_MODULE_INIT(/* exports, module, context /) {
Isolate
isolate = context->GetIsolate();

// Create a new instance of AddonData for this instance of the addon.
AddonData* data = new AddonData(isolate, exports);
// Wrap the data in a v8::External so we can pass it to the method we expose.
Local external = External::New(isolate, data);

// Expose the method “Method” to JavaScript, and make sure it receives the
// per-addon-instance data we created above by passing external as the
// third parameter to the FunctionTemplate constructor.
exports->Set(context,
String::NewFromUtf8(isolate, “method”, NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, Method, external)
->GetFunction(context).ToLocalChecked()).FromJust();
}

Worker support

In order to be loaded from multiple Node.js environments, such as a main thread and a Worker thread, an add-on needs to either:

Be an N-API addon, or
Be declared as context-aware using NODE_MODULE_INIT() as described above

In order to support Worker threads, addons need to clean up any resources they may have allocated when such a thread exists. This can be achieved through the usage of the AddEnvironmentCleanupHook() function:

void AddEnvironmentCleanupHook(v8::Isolate* isolate,
void (fun)(void arg),
void* arg);

This function adds a hook that will run before a given Node.js instance shuts down. If necessary, such hooks can be removed using RemoveEnvironmentCleanupHook() before they are run, which has the same signature. Callbacks are run in last-in first-out order.

The following addon.cc uses AddEnvironmentCleanupHook:

// addon.cc
#include <assert.h>
#include <stdlib.h>
#include <node.h>

using node::AddEnvironmentCleanupHook;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Object;

// Note: In a real-world application, do not rely on static/global data.
static char cookie[] = “yum yum”;
static int cleanup_cb1_called = 0;
static int cleanup_cb2_called = 0;

static void cleanup_cb1(void* arg) {
Isolate* isolate = static_cast<Isolate*>(arg);
HandleScope scope(isolate);
Local obj = Object::New(isolate);
assert(!obj.IsEmpty()); // assert VM is still alive
assert(obj->IsObject());
cleanup_cb1_called++;
}

static void cleanup_cb2(void* arg) {
assert(arg == static_cast<void*>(cookie));
cleanup_cb2_called++;
}

static void sanity_check(void*) {
assert(cleanup_cb1_called == 1);
assert(cleanup_cb2_called == 1);
}

// Initialize this addon to be context-aware.
NODE_MODULE_INIT(/* exports, module, context /) {
Isolate
isolate = context->GetIsolate();

AddEnvironmentCleanupHook(isolate, sanity_check, nullptr);
AddEnvironmentCleanupHook(isolate, cleanup_cb2, cookie);
AddEnvironmentCleanupHook(isolate, cleanup_cb1, isolate);
}

Test in JavaScript by running:

// test.js
require(’./build/Release/addon’);

Building

Once the source code has been written, it must be compiled into the binary addon.node file. To do so, create a file called binding.gyp in the top-level of the project describing the build configuration of the module using a JSON-like format. This file is used by node-gyp, a tool written specifically to compile Node.js Addons.

{
“targets”: [
{
“target_name”: “addon”,
“sources”: [ “hello.cc” ]
}
]
}

A version of the node-gyp utility is bundled and distributed with Node.js as part of npm. This version is not made directly available for developers to use and is intended only to support the ability to use the npm install command to compile and install Addons. Developers who wish to use node-gyp directly can install it using the command npm install -g node-gyp. See the node-gyp installation instructions for more information, including platform-specific requirements.

Once the binding.gyp file has been created, use node-gyp configure to generate the appropriate project build files for the current platform. This will generate either a Makefile (on Unix platforms) or a vcxproj file (on Windows) in the build/ directory.

Next, invoke the node-gyp build command to generate the compiled addon.node file. This will be put into the build/Release/ directory.

When using npm install to install a Node.js Addon, npm uses its own bundled version of node-gyp to perform this same set of actions, generating a compiled version of the Addon for the user’s platform on demand.

Once built, the binary Addon can be used from within Node.js by pointing require() to the built addon.node module:

// hello.js
const addon = require(’./build/Release/addon’);

console.log(addon.hello());
// Prints: ‘world’

Because the exact path to the compiled Addon binary can vary depending on how it is compiled (i.e. sometimes it may be in ./build/Debug/), Addons can use the bindings package to load the compiled module.

While the bindings package implementation is more sophisticated in how it locates Addon modules, it is essentially using a try…catch pattern similar to:

try {
return require(’./build/Release/addon.node’);
} catch (err) {
return require(’./build/Debug/addon.node’);
}

Linking to libraries included with Node.js

Node.js uses statically linked libraries such as V8, libuv and OpenSSL. All Addons are required to link to V8 and may link to any of the other dependencies as well. Typically, this is as simple as including the appropriate #include <…> statements (e.g. #include <v8.h>) and node-gyp will locate the appropriate headers automatically. However, there are a few caveats to be aware of:

When node-gyp runs, it will detect the specific release version of Node.js and download either the full source tarball or just the headers. If the full source is downloaded, Addons will have complete access to the full set of Node.js dependencies. However, if only the Node.js headers are downloaded, then only the symbols exported by Node.js will be available.

node-gyp can be run using the --nodedir flag pointing at a local Node.js source image. Using this option, the Addon will have access to the full set of dependencies.

Loading Addons using require()

The filename extension of the compiled Addon binary is .node (as opposed to .dll or .so). The require() function is written to look for files with the .node file extension and initialize those as dynamically-linked libraries.

When calling require(), the .node extension can usually be omitted and Node.js will still find and initialize the Addon. One caveat, however, is that Node.js will first attempt to locate and load modules or JavaScript files that happen to share the same base name. For instance, if there is a file addon.js in the same directory as the binary addon.node, then require(‘addon’) will give precedence to the addon.js file and load it instead.
Native Abstractions for Node.js

Each of the examples illustrated in this document make direct use of the Node.js and V8 APIs for implementing Addons. The V8 API can, and has, changed dramatically from one V8 release to the next (and one major Node.js release to the next). With each change, Addons may need to be updated and recompiled in order to continue functioning. The Node.js release schedule is designed to minimize the frequency and impact of such changes but there is little that Node.js can do currently to ensure stability of the V8 APIs.

The Native Abstractions for Node.js (or nan) provide a set of tools that Addon developers are recommended to use to keep compatibility between past and future releases of V8 and Node.js. See the nan examples for an illustration of how it can be used.
N-API

Stability: 2 - Stable

N-API is an API for building native Addons. It is independent from the underlying JavaScript runtime (e.g. V8) and is maintained as part of Node.js itself. This API will be Application Binary Interface (ABI) stable across versions of Node.js. It is intended to insulate Addons from changes in the underlying JavaScript engine and allow modules compiled for one version to run on later versions of Node.js without recompilation. Addons are built/packaged with the same approach/tools outlined in this document (node-gyp, etc.). The only difference is the set of APIs that are used by the native code. Instead of using the V8 or Native Abstractions for Node.js APIs, the functions available in the N-API are used.

Creating and maintaining an addon that benefits from the ABI stability provided by N-API carries with it certain implementation considerations.

To use N-API in the above “Hello world” example, replace the content of hello.cc with the following. All other instructions remain the same.

// hello.cc using N-API
#include <node_api.h>

namespace demo {

napi_value Method(napi_env env, napi_callback_info args) {
napi_value greeting;
napi_status status;

status = napi_create_string_utf8(env, “world”, NAPI_AUTO_LENGTH, &greeting);
if (status != napi_ok) return nullptr;
return greeting;
}

napi_value init(napi_env env, napi_value exports) {
napi_status status;
napi_value fn;

status = napi_create_function(env, nullptr, 0, Method, nullptr, &fn);
if (status != napi_ok) return nullptr;

status = napi_set_named_property(env, exports, “hello”, fn);
if (status != napi_ok) return nullptr;
return exports;
}

NAPI_MODULE(NODE_GYP_MODULE_NAME, init)

} // namespace demo

The functions available and how to use them are documented in C/C++ Addons with N-API.
Addon examples

Following are some example Addons intended to help developers get started. The examples make use of the V8 APIs. Refer to the online V8 reference for help with the various V8 calls, and V8’s Embedder’s Guide for an explanation of several concepts used such as handles, scopes, function templates, etc.

Each of these examples using the following binding.gyp file:

{
“targets”: [
{
“target_name”: “addon”,
“sources”: [ “addon.cc” ]
}
]
}

In cases where there is more than one .cc file, simply add the additional filename to the sources array:

“sources”: [“addon.cc”, “myexample.cc”]

Once the binding.gyp file is ready, the example Addons can be configured and built using node-gyp:

$ node-gyp configure build

Function arguments

Addons will typically expose objects and functions that can be accessed from JavaScript running within Node.js. When functions are invoked from JavaScript, the input arguments and return value must be mapped to and from the C/C++ code.

The following example illustrates how to read function arguments passed from JavaScript and how to return a result:

// addon.cc
#include <node.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;

// This is the implementation of the “add” method
// Input arguments are passed using the
// const FunctionCallbackInfo& args struct
void Add(const FunctionCallbackInfo& args) {
Isolate* isolate = args.GetIsolate();

// Check the number of arguments passed.
if (args.Length() < 2) {
// Throw an Error that is passed back to JavaScript
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate,
“Wrong number of arguments”,
NewStringType::kNormal).ToLocalChecked()));
return;
}

// Check the argument types
if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate,
“Wrong arguments”,
NewStringType::kNormal).ToLocalChecked()));
return;
}

// Perform the operation
double value =
args[0]

 类似资料:

相关阅读

相关文章

相关问答