1

以下の私のコードを参照してください:(コードをコンパイルするには: g++-4.7 demo.cpp -std=c++11 -lmsgpack)

#include <iostream>
#include <vector>
#include <sstream>
#include <string>
#include <msgpack.hpp>
using namespace std;

template<class T>
void pack(T &t, string &str)
{
  using namespace msgpack;
  sbuffer buff;
  pack(buff, t); 
  ostringstream is; 
  is << buff.size() << buff.data();
  str = string(is.str());
}

template<class T>
T unpack(string &str)
{
  using namespace msgpack;
  unpacked result;
  istringstream ss(str);
  int len;
  string buff;
  ss >> len >> buff;
  unpack(&result, buff.c_str(), len);

  auto obj = result.get();
  return obj.as<T>();
}

int main(int argc, char *argv[]) {
  vector<float> t = {1., 2., 3., 4., 5.};
  string s;
  pack(t, s); 
  auto r = unpack<vector<float> >(s);
  for(auto & v : r)
    std::cout << v << std::endl;
  // vector<int> is right
  /* 
  vector<int> t = {1, 2, 3, 4, 5};
  string s;
  pack(t, s); 
  auto r = unpack<vector<int> >(s);
  for(auto & v : r)
    std::cout << v << std::endl;
  */
  return 0;
}

'vector'、'vector'、'int'、'double' は上記のカプセル化で機能しますが、'vector'、'vector' は機能しないという奇妙なバグがあります。

実行時エラーは以下のように表示されます:

terminate called after throwing an instance of 'msgpack::type_error'
what():  std::bad_cast

ただし、以下のカプセル化では、どのタイプでもうまく機能します。

template<class T>
void pack(T &t, msgpack::sbuffer sbuf) {
  pack(&sbuf, t);
}

template<class T>
T unpack(const msgpack::sbuffer & sbuf) {
  msgpack::unpacked msg;
  msgpack::unpack(&msg, sbuf.data(), sbuf.size());
  auto obj = msg.get();
  return obj.as<t>();
}

私の最初のコードの問題は何ですか? ありがとう!

4

1 に答える 1

0

あなたの場合のように、msgpackバイナリ出力にはnullバイトが含まれる場合があります。is […] << buff.data();あなたの場合、最初の4バイトのみを出力します。

エラーを修正するには、 に置き換えis << buff.size() << buff.data();ますis << buff.size() << string(buff.data(), buff.size());

于 2014-01-14T21:34:00.097 に答える