使用 Node.js N-API 调用 C 函数时,不会显示预期的输出

Calling a C function with Node.js N-API shows output not expected

本文关键字:显示 输出 js Node N-API 调用 函数 使用      更新时间:2023-10-16

我是 Node.js N-API 的新手。让我直接回答这个问题。

我正在尝试使用 N-APICamellia_Ekeygen调用 C 函数,但函数m_uKttWork的输出与直接使用 C++ 代码调用同一函数不同。

以下是参考的代码和输出。

使用 N-API

模块.cpp

#include <node_api.h>
#include "camellia.h"
napi_value MyFunction(napi_env env, napi_callback_info info) {
typedef unsigned int KEY_TABLE_TYPE[68];
typedef unsigned char BYTE;
BYTE m_byCurrentWorkKey[16] {};
KEY_TABLE_TYPE m_uKttWork {};
napi_status status;
Camellia_Ekeygen( 128, m_byCurrentWorkKey, m_uKttWork );
napi_value result;
status = napi_create_array(env, &result);
napi_value num_result;
for (int i = 0; i < 68; i++) {
status = napi_create_uint32(env, m_uKttWork[i], &num_result);
status = napi_set_element(env, result, i, num_result);
}
return result;
}
napi_value Init(napi_env env, napi_value exports) {
napi_status status;
napi_value fn;
status = napi_create_function(env, NULL, 0, MyFunction, NULL, &fn);
status = napi_set_named_property(env, exports, "my_function", fn);
return exports;
}
NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)

模块.js

const addon = require('./build/Release/module');
console.log(addon.my_function());

输出

$ node module.js
[ 0,
0,
0,
0,
1827423791,
382301878,
1852628593,
3123771802,
0,
0,
0,
0,
588766488,
3143317110,
1865976676,
2093823798,
4002168422,
2604339595,
1169317293,
2610640796,
0,
0,
0,
0,
523455949,
2294675270,
0,
0,
2800143847,
4221767577,
1724826722,
292329323,
0,
0,
0,
0,
0,
0,
0,
0,
1169317293,
2610640796,
4002168422,
2604339595,
0,
0,
0,
0,
3143317110,
1865976676,
2093823798,
588766488,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0 ]
(node:3475) Warning: N-API is an experimental feature and could change at any time.
$ 

直接呼叫Camellia_Ekeygen

测试.cpp

#include <iostream>
#include "camellia.h"
int main() {
typedef unsigned char BYTE;
typedef unsigned int KEY_TABLE_TYPE[68];
BYTE m_byCurrentWorkKey[16] {};
KEY_TABLE_TYPE m_uKttWork {};
Camellia_Ekeygen( 128, m_byCurrentWorkKey, m_uKttWork );
for (int i = 0; i < 68; i++) {
std::cout << m_uKttWork[i] << " ";
}
std::cout << "n";
}

输出

$ g++ -std=c++11 -o test test.cpp Camellia.c 
$ ./test 
382301878 1827423791 0 0 1546120148 3860271694 623942010 872017868 1546120148 3860271694 1290497688 4155529454 4122759699 2305910053 1290497688 4155529454 2604339595 4002168422 2610640796 1169317293 4283709980 2844888938 4139420567 2122284241 0 0 3011048906 3223194901 2723350903 3007290908 1170374237 3194057156 0 0 0 0 1821862673 456472600 694825438 3002140226 3073371509 739572990 694825438 3002140226 3073371509 739572990 3672780383 4194169671 1865976676 3143317110 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
$ 

在这种情况下,我应该看什么吗?这几天我一直在寻找线索,但到目前为止仍然不知道。欢迎任何故障排除方向或参考。

我确定现在实际调用的Camellia_Ekeygen不是我提供的C++源文件中的那个。

我将函数重命名为Camellia_Ekeygen1module.cppcamellia.h和C++源文件,然后输出是预期的。

非常感谢您花时间阅读本文。