msgpack-c 已在问题和答案发布后更新。我想告知目前的情况。
从 msgpack-c 版本 2.0.0 开始支持 C 样式数组。见https://github.com/msgpack/msgpack-c/releases
msgpack-c 可以打包 const char 数组,例如“hello”。类型转换规则记录在https://github.com/msgpack/msgpack-c/wiki/v2_0_cpp_adaptor#predefined-adaptors。
char 数组映射到 STR。如果你想使用 BIN 而不是 STR,你需要用msgpack::type::raw_ref
. 那是包装概述。
以下是解包和转换说明:
https ://github.com/msgpack/msgpack-c/wiki/v2_0_cpp_object#conversion
解包意味着msgpack::object
从 MessagePack 格式的字节流创建。转换意味着从 . 转换为 C++ 对象msgpack::object
。
如果MessagePack 格式的数据是STR,并且隐蔽的目标类型是char 数组,则将数据复制到数组中,如果数组有多余的容量,则添加'\0'。如果 MessagePack 格式的数据是 BIN,则不添加“\0”。
这是基于原始问题的代码示例:
#include <msgpack.hpp>
#include <iostream>
inline
std::ostream& hex_dump(std::ostream& o, char const* p, std::size_t size ) {
o << std::hex << std::setw(2) << std::setfill('0');
while(size--) o << (static_cast<int>(*p++) & 0xff) << ' ';
return o;
}
int main() {
{
msgpack::sbuffer temp_sbuffer;
// since 2.0.0 char[] is supported.
// See https://github.com/msgpack/msgpack-c/wiki/v2_0_cpp_adaptor#predefined-adaptors
msgpack::pack(temp_sbuffer, "hello");
hex_dump(std::cout, temp_sbuffer.data(), temp_sbuffer.size()) << std::endl;
// packed as STR See https://github.com/msgpack/msgpack/blob/master/spec.md
// '\0' is not packed
auto oh = msgpack::unpack(temp_sbuffer.data(), temp_sbuffer.size());
static_assert(sizeof("hello") == 6, "");
char converted[6];
converted[5] = 'x'; // to check overwriting, put NOT '\0'.
// '\0' is automatically added if char-array has enought size and MessagePack format is STR
oh.get().convert(converted);
std::cout << converted << std::endl;
}
{
msgpack::sbuffer temp_sbuffer;
// since 2.0.0 char[] is supported.
// See https://github.com/msgpack/msgpack-c/wiki/v2_0_cpp_adaptor#predefined-adaptors
// packed as BIN
msgpack::pack(temp_sbuffer, msgpack::type::raw_ref("hello", 5));
hex_dump(std::cout, temp_sbuffer.data(), temp_sbuffer.size()) << std::endl;
auto oh = msgpack::unpack(temp_sbuffer.data(), temp_sbuffer.size());
static_assert(sizeof("hello") == 6, "");
char converted[7];
converted[5] = 'x';
converted[6] = '\0';
// only first 5 bytes are written if MessagePack format is BIN
oh.get().convert(converted);
std::cout << converted << std::endl;
}
}
运行演示:
https ://wandbox.org/permlink/mYJyYycfsQIwsekY