Are Node.js buffers in C++ addon null terminated?

此生再无相见时 提交于 2021-01-28 13:31:09

问题


I am trying to create buffer in a .js file, and then passing that buffer to a c++ addon where I will call a Windows API.

In the c++ addon I have:

auto buf = node::Buffer::Data(args[0]);
auto len = node::Buffer::Length(args[0]);

Are there any guarantees that node::Buffers are null-terminated? Or does node::Buffer::Length have any other form of safety check to prevent an overrun?


回答1:


No. Think of buffers as a minimal data structure containing length and memory; they are not raw memory like what malloc() provides. A buffer is protected against memory overruns within a JavaScript context but not if you pass a pointer to the buffer memory to C/C++. And because a Buffer can be used to store binary data (as well as a string) it doesn't provide an extra byte to null-terminate a string; it doesn't "know" what is in the buffer.

I don't think the code you've posted will work; This post does a good job of explaining how to use buffers in C/C++: https://community.risingstack.com/using-buffers-node-js-c-plus-plus/



来源:https://stackoverflow.com/questions/62667068/are-node-js-buffers-in-c-addon-null-terminated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!