【问题标题】:How to msgpack a user-defined C++ class with POD-arrays?如何使用 POD 数组 msgpack 用户定义的 C++ 类?
【发布时间】:2013-05-06 01:39:06
【问题描述】:

如何为用户定义的 C++ 类提供所有三个函数:msgpack_packmsgpack_unpackmsgpack_object(还有,它们的含义是什么?)(以相同的方式 @987654325 @ 是否适用于包含普通旧数据数组(例如 dobule[]char[])的非数组 POD/UD 类型,所以我的课程将与更高级别的课程很好地配合,在地图或矢量中包含此类?

有没有为您自己的类或至少 msgpack C++ api 文档实现它们的示例?

我发现的唯一可能的 api 参考链接是 http://redmine.msgpack.org/projects/msgpack/wiki ;但它现在已经死了。

说,我有一个类似的结构

struct entity {
  const char name[256];
  double mat[16];
};

什么是 msgpack_* 成员函数?

【问题讨论】:

  • 您的问题很好,并且以合理的方式提出。您至少还花费了一些精力来阅读文档。有些人会投反对票——可能是因为他们无法回答这个问题,并且因为错过了一些赞成票而感到蔑视。嘘他们。为你 +1。

标签: c++ api msgpack


【解决方案1】:

感谢为我的问题 -1 的人,我感到委屈并探索了 msgpack 的实际未记录代码库。以下是前面提到的函数的示例,其中有一些解释,我的理解量(由于缺少文档而非常不完整):

struct entity {
  char name[256];
  double mat[16];

  // this function is appears to be a mere serializer
  template <typename Packer>
  void msgpack_pack(Packer& pk) const {
    // make array of two elements, by the number of class fields
    pk.pack_array(2); 

    // pack the first field, strightforward
    pk.pack_raw(sizeof(name));
    pk.pack_raw_body(name, sizeof(name));

    // since it is array of doubles, we can't use direct conversion or copying
    // memory because it would be a machine-dependent representation of floats
    // instead, we converting this POD array to some msgpack array, like this:
    pk.pack_array(16);
    for (int i = 0; i < 16; i++) {
      pk.pack_double(mat[i]);
    }
  }

  // this function is looks like de-serializer, taking an msgpack object
  // and extracting data from it to the current class fields
  void msgpack_unpack(msgpack::object o) {
    // check if received structure is an array
    if(o.type != msgpack::type::ARRAY) { throw msgpack::type_error(); }

    const size_t size = o.via.array.size;

    // sanity check
    if(size <= 0) return;
    // extract value of first array entry to a class field
    memcpy(name, o.via.array.ptr[0].via.raw.ptr, o.via.array.ptr[0].via.raw.size);

    // sanity check
    if(size <= 1) return;
    // extract value of second array entry which is array itself:
    for (int i = 0; i < 16 ; i++) {
      mat[i] = o.via.array.ptr[1].via.array.ptr[i].via.dec;
    }
  }

  // destination of this function is unknown - i've never ran into scenary
  // what it was called. some explaination/documentation needed.
  template <typename MSGPACK_OBJECT>
  void msgpack_object(MSGPACK_OBJECT* o, msgpack::zone* z) const { 

  }
};

【讨论】:

    猜你喜欢
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多