How to create a new Buffer from a vector of char using node-addon-api?

1.2k Views Asked by At

I'm trying to create a new Buffer from a vector of char using node-addon-api, but the resulting Buffer's content is always different from the vector. Here is my cpp code:

#include <napi.h>

Napi::Value GetBuffer(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();
  std::vector<char> v{0x10, 0x11, 0x12};
  return Napi::Buffer<char>::New(env, v.data(), v.size());
}

Napi::Object Init(Napi::Env env, Napi::Object exports) {
  exports.Set(Napi::String::New(env, "getBuffer"), Napi::Function::New(env, GetBuffer));
  return exports;
}

NODE_API_MODULE(addon, Init);

Here is my js code:

const addon = require('./build/Release/addon');
const buffer = addon.getBuffer();
console.log(buffer.toString("hex")); // The output is different every time, instead of being 101112

The resulting buffer's contents are always different, why? How to make it right?

1

There are 1 best solutions below

0
On

It is because in the Buffer's constructor you passed the address of a temporary object that got deallocated as soon as the function returned.

If you create the buffer by copying the content of the vector it'll work:

Napi::Value GetBuffer(const Napi::CallbackInfo& info) {
  Napi::Env env = info.Env();
  std::vector<char> v{0x10, 0x11, 0x12};
  return Napi::Buffer<char>::Copy(env, v.data(), v.size());
}