设置:
我有一个 NODE.JS 应用程序,它必须以低延迟执行一些计算
我决定使用 N-API 和 node-gyp 将本机 C++ 模块包含到 NODE.JS 应用程序中
当前状态:
我已经到了工具链工作的地步,我可以将 C++ 源代码编译成二进制文件,在 NODE.JS 应用程序中包含二进制模块,NODE.JS 应用程序执行
我可以使用标准 NODE.JS 调用 C++ 方法来自 NODE.JS 的类型和方法可以在执行完成后将标准 NODE.JS 类型返回给 NODE.JS
问题:
我不知道如何将自定义类型/对象从 C++ 返回到 NODE.JS
目前我想基本上返回一个具有多种类型的结构,以便将复杂解析的结果返回给 NODE.JS单个 NODE.JS 调用
最少的代码输出:
我做了一个最小的实现来展示我想做的事情。如果您评论#define ENABLE_RETURN_CLASS
代码仅使用标准的 NODE.JS 类型并且一切正常。在输出图像下方,显示工具链和执行按预期工作:
如果留下#define ENABLE_RETURN_CLASS
代码编译失败。据我了解,它不了解如何从 C++ 对象转换为 NODE.JS 对象。这是错误:
最少的代码:
初始化 NODE.JS 应用程序
npm init
npm install node-gyp --save-dev
npm install node-addon-api
将 C++ 二进制文件编译成 NODE.JS 模块
npm run build
启动 NODE.JS 应用程序
node main.js
该代码可以在此存储库中找到:
https
://github.com/OrsoEric/2020-01-18-Test-NODEJS-Return-Class
我计划在找到解决方案后对其进行更新。
我要返回到 NODE.JS 应用程序的类的代码:
my_class.h
namespace User
{
//Class I want to return to NODE.JS
class My_class
{
public:
//Constructor
My_class( void );
//Public references
float &my_float( void );
int &my_int( void );
private:
//Private class vars
float g_my_float;
int g_my_int;
};
} //End namestace: User
my_class.cpp
#include <iostream>
//Class header
#include "my_class.h"
namespace User
{
//Constructor
My_class::My_class( void )
{
this -> g_my_float = (float)1.001;
this -> g_my_int = (int)42;
}
//Public Reference
float &My_class::my_float( void )
{
return this -> g_my_float;
}
//Public Reference
int &My_class::my_int( void )
{
return this -> g_my_int;
}
} //End namestace: User
C++ 和 NODE.JS 之间的绑定代码。#define ENABLE_RETURN_CLASS
启用返回类的代码。本例中的实例是一个全局变量。
node_bindings.cpp
//NODE bindings
#include <napi.h>
//C++ Class I want to return to NODE.JS
#include "my_class.h"
//Comment to disable the code that return the class instance
//#define ENABLE_RETURN_CLASS
//Instance of My_class I want to return to NODE.JS
User::My_class g_instance;
//Prototype of function called by NODE.JS that initializes this module
extern Napi::Object init(Napi::Env env, Napi::Object exports);
//Prototype of function that returns a standard type: WORKS
extern Napi::Number get_my_float(const Napi::CallbackInfo& info);
#ifdef ENABLE_RETURN_CLASS
//Prototype of function that returns My_class to NODE.JS: DOES NOT WORK!!!
extern Napi::Object get_my_class(const Napi::CallbackInfo& info);
#endif // ENABLE_RETURN_CLASS
//Initialize instance
Napi::Object init(Napi::Env env, Napi::Object exports)
{
//Construct the instance of My_class I want to return to NODE.JS
g_instance = User::My_class();
//Register methods accessible from the outside in the NODE.JS environment
//Return a standard type
exports.Set( "get_my_float", Napi::Function::New(env, get_my_float) );
#ifdef ENABLE_RETURN_CLASS
//Return the whole class
exports.Set( "get_my_class", Napi::Function::New(env, get_my_class) );
#endif
return exports;
} //End function: init | Napi::Env | Napi::Object
//Interface between function and NODE.JS
Napi::Number get_my_float(const Napi::CallbackInfo& info)
{
Napi::Env env = info.Env();
//Check arguments
if (info.Length() != 0)
{
Napi::TypeError::New(env, "ERR: Expecting no arguments").ThrowAsJavaScriptException();
}
//Get the return value
float tmp = g_instance.my_float();
//Return a NODE.JS number
return Napi::Number::New(env, (float)tmp);
} //End Function: get_my_float | Napi::CallbackInfo&
#ifdef ENABLE_RETURN_CLASS
//Interface between function and NODE.JS
Napi::Object get_my_class(const Napi::CallbackInfo& info)
{
Napi::Env env = info.Env();
//Check arguments
if (info.Length() != 0)
{
Napi::TypeError::New(env, "ERR: Expecting no arguments").ThrowAsJavaScriptException();
}
//Get the return value
User::My_class tmp = g_instance;
//Return a NODE.JS number
return Napi::Object::New(env, (User::My_class)tmp);
} //End Function: get_my_float | Napi::CallbackInfo&
#endif // ENABLE_RETURN_CLASS
NODE_API_MODULE( My_cpp_module, init )
NODE.JS 应用程序main.js包含并执行 C++ 模块:
//Include native C++ module
const my_custom_cpp_module = require('./build/Release/MyCustomCppModule.node');
console.log('My custom c++ module',my_custom_cpp_module);
//TEST:
tmp = my_custom_cpp_module.get_my_float();
console.log( tmp );
module.exports = my_custom_cpp_module;
绑定在文件binding.gyp中描述:
{
"targets": [{
"target_name": "MyCustomCppModule",
"cflags!": [ "-fno-exceptions" ],
"cflags_cc!": [ "-fno-exceptions" ],
"sources": [
"node_bindings.cpp",
"my_class.cpp"
],
'include_dirs': [
"<!@(node -p \"require('node-addon-api').include\")"
],
'libraries': [],
'dependencies': [
"<!(node -p \"require('node-addon-api').gyp\")"
],
'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ]
}]
}
而package.json是 NODE.JS 解析依赖项所需要的,编译并运行
{
"name": "2020-01-18-test-return-object",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"build": "node-gyp rebuild",
"clean": "node-gyp clean"
},
"author": "",
"license": "ISC",
"gypfile": true,
"devDependencies": {
"node-gyp": "^6.1.0"
},
"dependencies": {
"node-addon-api": "^2.0.0"
}
}
解决方案
我无法在 Napi::Object 中放置自定义类,但我可以创建一个空的 Napi::Object 并一个一个地创建字段。 https://github.com/OrsoEric/2020-01-18-Test-NODEJS-Return-Class
在 node_bindings.cpp 中实现 Napi ::Object 的正确构造
//NODE bindings
#include <napi.h>
//C++ Class I want to return to NODE.JS
#include "my_class.h"
//Comment to disable the code that return the class instance
#define ENABLE_RETURN_CLASS
//Instance of My_class I want to return to NODE.JS
User::My_class g_instance;
//Prototype of function called by NODE.JS that initializes this module
extern Napi::Object init(Napi::Env env, Napi::Object exports);
//Prototype of function that returns a standard type: WORKS
extern Napi::Number get_my_float(const Napi::CallbackInfo& info);
#ifdef ENABLE_RETURN_CLASS
//Prototype of function that returns My_class to NODE.JS: DOES NOT WORK!!!
extern Napi::Object get_my_class(const Napi::CallbackInfo& info);
#endif // ENABLE_RETURN_CLASS
//Initialize instance
Napi::Object init(Napi::Env env, Napi::Object exports)
{
//Construct the instance of My_class I want to return to NODE.JS
g_instance = User::My_class();
//Register methods accessible from the outside in the NODE.JS environment
//Return a standard type
exports.Set( "get_my_float", Napi::Function::New(env, get_my_float) );
#ifdef ENABLE_RETURN_CLASS
//Return the whole class
exports.Set( "get_my_class", Napi::Function::New(env, get_my_class) );
#endif
return exports;
} //End function: init | Napi::Env | Napi::Object
//Interface between function and NODE.JS
Napi::Number get_my_float(const Napi::CallbackInfo& info)
{
Napi::Env env = info.Env();
//Check arguments
if (info.Length() != 0)
{
Napi::TypeError::New(env, "ERR: Expecting no arguments").ThrowAsJavaScriptException();
}
//Get the return value
float tmp = g_instance.my_float();
//Return a NODE.JS number
return Napi::Number::New(env, (float)tmp);
} //End Function: get_my_float | Napi::CallbackInfo&
#ifdef ENABLE_RETURN_CLASS
//Interface between function and NODE.JS
Napi::Object get_my_class(const Napi::CallbackInfo& info)
{
Napi::Env env = info.Env();
//Check arguments
if (info.Length() != 0)
{
Napi::TypeError::New(env, "ERR: Expecting no arguments").ThrowAsJavaScriptException();
}
//Get a copy of the instance of the class I want to return
User::My_class tmp = g_instance;
//Construct empty return object in the NODE.JS environment
Napi::Object ret_tmp = Napi::Object::New( env );
//Manually create and fill the fields of the return object
ret_tmp.Set("my_float", Napi::Number::New( env, (float)tmp.my_float() ));
ret_tmp.Set("my_int", Napi::Number::New( env, (int)tmp.my_int() ));
//Return a NODE.JS Object
return (Napi::Object)ret_tmp;
} //End Function: get_my_class | Napi::CallbackInfo&
#endif // ENABLE_RETURN_CLASS
NODE_API_MODULE( My_cpp_module, init )
在main.js中添加测试指令:
//Include native C++ module
const my_custom_cpp_module = require('./build/Release/MyCustomCppModule.node');
console.log('My custom c++ module',my_custom_cpp_module);
//TEST: Standard NODE.JS type
tmp = my_custom_cpp_module.get_my_float();
console.log( tmp );
//Custom NODE.JS type
class_tmp = my_custom_cpp_module.get_my_class();
console.log( class_tmp );
module.exports = my_custom_cpp_module;