【问题标题】:Union in thrift shows all values setted in c++thrift 中的 Union 显示在 c++ 中设置的所有值
【发布时间】:2016-05-31 00:39:01
【问题描述】:

我做了三个字段的简单联合

union example{
    1:string STRING,
    2:i64 INT64,
    3:double DOUBLE
}

我将客户端中的示例联合实例化为:

example ex;
ex.__set_STRING("Example");
ex.__isset.STRING = true;

并通过接受示例作为参数的方法发送示例

在服务器中,被调用的方法是这样完成的:

void get(const example &ex)
  {
    cout << ex.__isset.STRING << ' ' << ex.__isset.INT64 << ' ' <<
        ex.__isset.DOUBLE << endl;
    cout << ex << endl;
  }

奇怪的是这样一个小程序的输出是:

1 1 1
example(STRING="Example", INT64=0, DOUBLE=0)

我不知道这是否是设置联合类型的正确方法,但我尝试了几种组合,但似乎都没有。

sn-p 的来源可以在这里找到:https://github.com/enriquefynn/union_thrift

【问题讨论】:

  • example ex;之后尝试memset(&amp;ex, 0, sizeof(ex));
  • 或者手动设置__isset.INT64 = __isset.DOUBLE = false;
  • 已经试过了,不行:/
  • 请发布 thrift 为客户端和服务器端序列化生成的代码。
  • 我只是将此代码附加到教程 cpp 代码中。这个问题很容易重现。

标签: c++ thrift


【解决方案1】:
uint32_t type_ex::write(::apache::thrift::protocol::TProtocol* oprot) const {
  uint32_t xfer = 0;
  apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot);
  xfer += oprot->writeStructBegin("type_ex");

  xfer += oprot->writeFieldBegin("STRING", ::apache::thrift::protocol::T_STRING, 1);
  xfer += oprot->writeString(this->STRING);
  xfer += oprot->writeFieldEnd();

  xfer += oprot->writeFieldBegin("INT64", ::apache::thrift::protocol::T_I64, 2);
  xfer += oprot->writeI64(this->INT64);
  xfer += oprot->writeFieldEnd();

  xfer += oprot->writeFieldBegin("DOUBLE", ::apache::thrift::protocol::T_DOUBLE, 3);
  xfer += oprot->writeDouble(this->DOUBLE);
  xfer += oprot->writeFieldEnd();

  xfer += oprot->writeFieldStop();
  xfer += oprot->writeStructEnd();
  return xfer;
}

看起来像是工会的错误。这些值是无条件写入的,它适用于struct,但不适用于union。因此,解决方法是添加明确的optional

union type_ex
{
    1 : optional string STRING,
    2 : optional i64 INT64,
    3 : optional double DOUBLE
}

这给了我们:

uint32_t type_ex::write(::apache::thrift::protocol::TProtocol* oprot) const {
  uint32_t xfer = 0;
  apache::thrift::protocol::TOutputRecursionTracker tracker(*oprot);
  xfer += oprot->writeStructBegin("type_ex");

  if (this->__isset.STRING) {
    xfer += oprot->writeFieldBegin("STRING", ::apache::thrift::protocol::T_STRING, 1);
    xfer += oprot->writeString(this->STRING);
    xfer += oprot->writeFieldEnd();
  }
  if (this->__isset.INT64) {
    xfer += oprot->writeFieldBegin("INT64", ::apache::thrift::protocol::T_I64, 2);
    xfer += oprot->writeI64(this->INT64);
    xfer += oprot->writeFieldEnd();
  }
  if (this->__isset.DOUBLE) {
    xfer += oprot->writeFieldBegin("DOUBLE", ::apache::thrift::protocol::T_DOUBLE, 3);
    xfer += oprot->writeDouble(this->DOUBLE);
    xfer += oprot->writeFieldEnd();
  }
  xfer += oprot->writeFieldStop();
  xfer += oprot->writeStructEnd();
  return xfer;
}

Bug report filed.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-18
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    • 2016-03-15
    • 2015-01-30
    • 1970-01-01
    相关资源
    最近更新 更多