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?