我有以下不明白的情况。我有一个应用程序来自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)
当我向NodeJS发送我的char变量时,我得到80字节,但它们充满了随机值。在创建str
之前,看起来NewBuffer()
变量所指向的位置已被回收。
我希望得到有关正在发生的事情的解释,并理想地获得潜在的解决方案。
答案 0 :(得分:1)
根据documentation,NewBuffer
假设数据的所有权已转移到缓冲区本身。
您的char数组根本没有复制,如果它的范围熄灭,就会消失,因此您会产生未定义的行为。
您应该在动态内存上分配数组,让缓冲区获得它的所有权来解决问题
换句话说,使用new
运算符分配字符数组,将其传递给NewBuffer
并不要删除它。
答案 1 :(得分:1)
我认为问题是char str[80];
将在堆栈中分配,一旦你的Combine
方法完成,它将被解除分配(从堆栈弹出)并被其他被推入的东西覆盖堆栈。
将其声明为char* str;
并使用str = new char[80];
动态分配。然后使用strcpy和strcat进行所有初始化。