c++ - 从 C++ 将缓冲区传递给 NodeJS 时,我的数据消失了

标签 c++ node.js node.js-nan

我有以下情况,我不明白。我有一个应用程序,我从 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/

相关文章:

c++ - 同一解决方案中项目之间的链接问题(Exe依赖于Lib)

c++ - 具有相同名称的 Getter/Setter

c++ - 我应该避免在 C++ 中使用#define 吗?为什么,我可以使用哪些替代方案?

c++ - 在哪里放置 2 个文件的辅助函数?

c++ - NodeJS Addon 从 NAN AsyncWorker::Execute 内部调用 Javascript 回调

javascript - jQuery.ajax#get 之后出现意外的 token 冒号 JSON

windows - npm 链接不起作用(Windows);将 git 和 node.js 用于 lexandra/Aardwolf.git

json - PostgreSQL和nodejs/pg,返回嵌套的JSON

c++ - 如何检查对象是否是 Nan 2 中构造函数的实例?

node.js-addon - 将旧插件迁移到 NAPI