gpt4 book ai didi

c++ - 如何将 C++ 类返回到 NODE.JS

转载 作者:太空宇宙 更新时间:2023-11-03 21:50:31 25 4
gpt4 key购买 nike

设置:
我有一个 NODE.JS 应用程序,必须以低延迟执行一些计算
我决定使用 N-API 和 node-gyp 将 native C++ 模块包含到 NODE.JS 应用程序

当前状态:
我已经到了工具链工作的地步,我可以将 C++ 源代码编译成二进制文件,将二进制模块包含在 NODE.JS 应用程序中,NODE.JS 应用程序执行
我可以从 NODE.JS 调用具有标准 NODE.JS 类型的 C++ 方法,并且这些方法在执行完成后可以将标准 NODE.JS 类型返回到 NODE.JS

问题:
我不知道如何将自定义类型/对象从 C++ 返回到 NODE.JS
目前我想基本上返回一个具有多种类型的结构,以便在单个 NODE.JS 调用中将复杂解析的结果返回给 NODE.JS

最小代码输出:
我做了一个最小的实现来展示我想做的事情。如果您注释#define ENABLE_RETURN_CLASS,则代码仅使用标准 NODE.JS 类型,并且一切正常。下面是输出图像,显示了工具链和执行情况:
float works

如果您离开#define ENABLE_RETURN_CLASS,代码将无法编译。据我所知,它不理解如何从 C++ 对象转换为 NODE.JS 对象。这是错误: enter image description here

最少代码:
初始化 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 之间的绑定(bind)代码。 #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;

绑定(bind)在文件 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;

输出:
enter image description here

最佳答案

我认为,如 Napi::Object docs 中所述,您不能使用自定义类实例化对象。只有原始值。因此,我建议创建一个空的 Napi::Object 并使用其 Set 来映射值。

Napi::Object ret = Napi::Object::New(env);

ret.Set("my_float", Napi::Number::New(env, (float)tmp.my_float()));

填写所有字段并返回对象。就像您对 exports

所做的那样

关于c++ - 如何将 C++ 类返回到 NODE.JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59799509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com