我有以下情况,我不明白。我有一个应用程序,我从 NodeJS 中使用 Nan 调用 C++ 函数。 C++端代码如下:
#include <nan.h>
#include <iostream>
using namespace std;
using namespace Nan;
using namespace v8;
//
// The function that we are going to call from NodeJS
//
NAN_METHOD(Combine)
{
char str[80];
strcpy (str,"these ");
strcat (str,"strings ");
strcat (str,"are ");
strcat (str,"concatenated.");
//
// Send the buffer back to NodeJS with the result of our calculation.
//
info
.GetReturnValue()
.Set(
NewBuffer((char *) str, 80)
.ToLocalChecked());
}
//
// The constructor
//
NAN_MODULE_INIT(Init)
{
//
// Expose the method or methods to NodeJS
//
Nan::Set(
target,
New<String>("combine").ToLocalChecked(),
GetFunction(New<FunctionTemplate>(Combine)).ToLocalChecked()
);
}
//
// Load the constructor
//
NODE_MODULE(basic_nan, Init)
当我将我的 char 变量发送回 NodeJS 时,我得到了 80 个字节,但它们充满了随机值。看起来好像在创建 NewBuffer()
之前回收了 str
变量指向的地方。
我的问题
我想得到有关正在发生的事情的解释,并理想地得到一个潜在的解决方案 🙂。
最佳答案
我认为问题在于 char str[80];
将在堆栈中分配,一旦您的 Combine
方法完成,它将被释放(从stack) 并被插入堆栈的其他内容覆盖。
将其声明为 char* str;
并使用 str = new char[80];
动态分配它。然后使用 strcpy 和 strcat 进行所有这些初始化。
关于c++ - 从 C++ 将缓冲区传递给 NodeJS 时,我的数据消失了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39982351/