msgpack
MessagePack 是一种高效的二进制序列化格式,可在多种语言之间交换数据,但它更快、更小。小整数被编码为单个字节,而短字符串除了字符串本身之外只需要一个额外的字节。
msgpackcxx使用指南
msgpackcxx是一个纯头文件库。
安装指南:
git clone https://github.com/msgpack/msgpack-c.git
cd msgpack-c
git checkout cpp_master
mkdir build && cd build
mkdir install_output # 安装到指定目录,然后复制集成到自己的项目中
cmake -DMSGPACK_CXX14=ON -DCMAKE_INSTALL_PREFIX=./install_output -DMSGPACK_USE_BOOST=OFF .. # 去掉对boost的依赖、使用c++14
cmake --build . --target install
安装后会在install_output
目录出现include
和lib
,复制到自己项目的thirdparty/msgpack下。
CMakeLists.txt 参考如下:
# add_definitions(-DMSGPACK_USE_BOOST=OFF)
set(MSGPACK_LOCAL_DIR "${PROJECT_ROOT_DIR}/thirdparty/msgpack-c")
set(Msgpackcxx_DIR "${MSGPACK_LOCAL_DIR}/lib/cmake/msgpack-cxx")
find_package(msgpack-cxx REQUIRED NO_DEFAULT_PATH PATHS ${Msgpackcxx_DIR})
set(MSGPACK_INCLUDE_DIRS "${MSGPACK_LOCAL_DIR}/include")
include_directories(${MSGPACK_INCLUDE_DIRS})
add_executable(test_msgpack test.cpp)
target_link_libraries(test_msgpack PRIVATE msgpack-cxx)
test.cpp
#include <msgpack.hpp>
#include <vector>
#include <string>
#include <iostream>
int main(void) {
// serializes this object.
std::vector<std::string> vec;
vec.push_back("Hello");
vec.push_back("MessagePack");
// serialize it into simple buffer.
msgpack::sbuffer sbuf;
msgpack::pack(sbuf, vec);
// deserialize it.
msgpack::object_handle oh =
msgpack::unpack(sbuf.data(), sbuf.size());
// print the deserialized object.
msgpack::object obj = oh.get();
std::cout << obj << std::endl; //=> ["Hello", "MessagePack"]
// convert it into statically typed object.
std::vector<std::string> rvec;
obj.convert(rvec);
}