问题
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