使用Node.js Addon實現類繼承
本文轉載自微信公眾號「編程雜技」,作者theanarkh。轉載本文請聯系編程雜技公眾號。
前言:昨天有個同學問怎么通過NAPI把C++類的繼承關系映射到JS,很遺憾,NAPI貌似還不支持,但是V8支持,因為V8在頭文件里導出了這些API,并Node.js里也依賴這些API,所以可以說是比較穩定的。本文介紹一下如何實現這種映射(不確定是否能滿足這位同學的需求)。
下面我們看一下Addon的實現。會涉及到V8的一些使用,可以先閱讀該文章《一段js理解nodejs中js調用c++/c的過程》。首先看一下基類的實現。
- #ifndef BASE_H
- #define BASE_H
- #include <stdio.h>
- #include <node.h>
- #include <node_object_wrap.h>
- using namespace node;
- using namespace v8;
- class Base: public ObjectWrap {
- public:
- static void New(const FunctionCallbackInfo<Value>& info) {
- // 新建一個對象,然后包裹到info.This()中,后面會解包出來使用
- Base* base = new Base();
- base->Wrap(info.This());
- }
- static void Print(const FunctionCallbackInfo<Value>& info) {
- // 解包出來使用
- Base* base = ObjectWrap::Unwrap<Base>(info.This());
- base->print();
- }
- void print() {
- printf("base print\n");
- }
- void hello() {
- printf("base hello\n");
- }
- };
- #endif
Node.js提供的ObjectWrap類實現了Wrap和UnWrap的功能,所以我們可以繼承它簡化封包解包的邏輯。Base類定義了兩個功能函數hello和print,同時定義了兩個類靜態函數New和Print。New函數是核心邏輯,該函數在js層執行new Base的時候會執行并傳入一個對象,這時候我們首先創建一個真正的有用的對象,并且通過Wrap把該對象包裹到傳進來的對象里。我們繼續看一下子類。
- #ifndef DERIVED_H
- #define DERIVED_H
- #include <node.h>
- #include <node_object_wrap.h>
- #include"Base.h"
- using namespace node;
- using namespace v8;
- class Derived: public Base {
- public:
- static void New(const FunctionCallbackInfo<Value>& info) {
- Derived* derived = new Derived();
- derived->Wrap(info.This());
- }
- static void Hello(const FunctionCallbackInfo<Value>& info) {
- Derived* derived = ObjectWrap::Unwrap<Derived>(info.This());
- // 調用基類的函數
- derived->hello();
- }
- };
- #endif
子類的邏輯類似,New函數和基類的邏輯一樣,除了繼承基類的方法外,額外定義了一個Hello函數,但是我們看到這只是個殼子,底層還是調用了基類的函數。定義完基類和子類后,我們把這兩個類導出到JS。
- #include <node.h>
- #include "Base.h"
- #include "Derived.h"
- namespace demo {
- using v8::FunctionCallbackInfo;
- using v8::Isolate;
- using v8::Local;
- using v8::Object;
- using v8::String;
- using v8::Value;
- using v8::FunctionTemplate;
- using v8::Function;
- using v8::Number;
- using v8::MaybeLocal;
- using v8::Context;
- using v8::Int32;
- using v8::NewStringType;
- void Initialize(
- Local<Object> exports,
- Local<Value> module,
- Local<Context> context
- ) {
- Isolate * isolate = context->GetIsolate();
- // 新建兩個函數模板,基類和子類,js層New導出的函數時,V8會執行New函數并傳入一個對象
- Local<FunctionTemplate> base = FunctionTemplate::New(isolate, Base::New);
- Local<FunctionTemplate> derived = FunctionTemplate::New(isolate, Derived::New);
- // js層使用的類名
- NewStringType type = NewStringType::kNormal;
- Local<String> base_string = String::NewFromUtf8(isolate, "Base", type).ToLocalChecked();
- Local<String> derived_string = String::NewFromUtf8(isolate, "Derived", type).ToLocalChecked();
- // 預留一個指針空間
- base->InstanceTemplate()->SetInternalFieldCount(1);
- derived->InstanceTemplate()->SetInternalFieldCount(1);
- // 定義兩個函數模板,用于屬性的值
- Local<FunctionTemplate> BasePrint = FunctionTemplate::New(isolate, Base::Print);
- Local<FunctionTemplate> Hello = FunctionTemplate::New(isolate, Derived::Hello);
- // 給基類定義一個print函數
- base->PrototypeTemplate()->Set(isolate, "print", BasePrint);
- // 給子類定義一個hello函數
- derived->PrototypeTemplate()->Set(isolate, "hello", Hello);
- // 建立繼承關系
- derived->Inherit(base);
- // 導出兩個函數給js層
- exports->Set(context, base_string, base->GetFunction(context).ToLocalChecked()).Check();
- exports->Set(context, derived_string, derived->GetFunction(context).ToLocalChecked()).Check();
- }
- NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME, Initialize)
- }
我們看到給基類原型定義了一個print函數,給子類定義了hello函數。最后我們看看如何在JS層使用。
- const { Base, Derived } = require('./build/Release/test.node');
- const base = new Base();
- const derived = new Derived();
- base.print();
- derived.hello();
- derived.print();
- console.log(derived instanceof Base, derived instanceof Derived)
下面是具體的輸出
- base print
- base hello
- base print
- true true
我們逐句分析
1 base.print()比較簡單,就是調用基類定義的Print函數。
2 derived.hello()看起來是調用了子類的Hello函數,但是Hello函數里調用了基類的hello函數,實現了邏輯的復用。
3 derived.print()子類沒有實現print函數,這里調用的是基類的print函數,和1一樣。
4 derived instanceof Base, derived instanceof Derived。根據我們的定義,derived不僅是Derived的實例,也是Base的實例。
實現代碼分析完了,我們看到把C++類映射到JS的方式有兩種,第一種就是兩個C++ 類沒有繼承關系,通過V8的繼承API實現兩個JS層存在繼承關系的類(函數),比如print函數的實現,我們看到子類沒有實現print,但是可以調用print,因為基類定義了,Node.js就是這樣處理的。第二種就是兩個存在繼承關系的C++類,同樣先通過V8的API實現兩個繼承的類導出到JS使用,因為JS層使用的只是殼子,具體執行到C++代碼的時候,我們再體現出這種繼承關系。比如Hello函數的實現,雖然我們是在子類里導出了hello函數,并且JS執行hello的時候的確執行到了子類的C++代碼,但是最后會調用基類的hello函數。
最后我們通過Nodej.js看看是如何做這種映射的,我們通過PipeWrap.cc的實現進行分析。
- // 新建一個函數模板
- Local<FunctionTemplate> t = env->NewFunctionTemplate(New);// 繼承兩個函數模板
- t->Inherit(LibuvStreamWrap::GetConstructorTemplate(env));// 導出給JS使用
- exports->Set(env->context(),
- pipeString,
- t->GetFunction(env->context()).ToLocalChecked()).Check();
上面代碼實現了繼承,我們看看GetConstructorTemplate的實現。
- tmpl = env->NewFunctionTemplate(nullptr);
- env->SetProtoMethod(tmpl, "setBlocking", SetBlocking);
- env->SetProtoMethod(tmpl, "readStart", JSMethod<&StreamBase::ReadStartJS>);
- env->SetProtoMethod(t, "readStop", JSMethod<&StreamBase::ReadStopJS>);// ...
上面代碼新建了一個新的函數模板并且設置了一系列的原型屬性,那么模板t就繼承了這些屬性。我們看看Node.js里怎么使用的。
- function createHandle(fd, is_server) {
- // ...
- return new Pipe(
- is_server ? PipeConstants.SERVER : PipeConstants.SOCKET
- );}
- this._handle = createHandle(fd, false);
- err = this._handle.setBlocking(true);
上面的代碼首先會創建一個Pipe對象,然后調用它的setBlocking方法。我們發現Pipe(pipe_wrap.cc)是沒有實現setBlocking函數的,但是好為什么他可以調用setBlocking呢?答案就是它的基類實現了。
后記:在JS里實現繼承是簡單的,但是在底層實現起來還是比較復雜的,但是從代碼設計的角度來看是非常有必要的。
代碼可以在倉庫獲取:
https://github.com/theanarkh/learn-to-write-nodejs-addons。