1

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?

0

1 Answer 1

3

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());
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.