【问题标题】:C++ HDF5 extract one member of a compound data typeC++ HDF5 提取复合数据类型的一个成员
【发布时间】:2017-06-06 13:21:36
【问题描述】:

我正在编写一个读取由另一个库生成的 hdf5 文件的 c++ 库。

那些 hdf5 文件包含大量具有各种复合数据类型的复合数据集。我希望将每种复合数据类型转换为 C++ 结构。

对于字符串(可变长度或固定大小的字符数组),我想在 C++ 结构中使用 std::string。

目前,我使用中间 C 结构(使用 char*char[] 变量),然后将其转换为最终的 C++ 结构。但是,这会导致大量样板代码。

如果我可以按成员提取数据成员,我可以执行以下操作:

std::string name = extract<std::string>(d,"name");

其中 d 是复合数据集。

有没有可能

【问题讨论】:

  • 您想提取的成员总是字符串吗?还是它们有许多不同的数据类型?
  • 成员有混合类型。

标签: c++ hdf


【解决方案1】:

我找到了一个可行的解决方案。我把它贴在这里,也许有人会觉得它有用。这个想法是创建一个 CompoundExtractor 对象,该对象包含一个缓冲区,在该缓冲区中读取整个化合物。然后,可以使用模板提取方法将成员一一提取。在这个阶段,适当的专业化(此处未报告)允许对字符串进行适当的处​​理。 问候,

struct MADNEX_VISIBILITY_EXPORT CompoundExtractor
{
  /*!
   * \brief constructor
   * \param[in] d: data set
   */
  CompoundExtractor(const DataSet&);
  //! destructor
  ~CompoundExtractor();
  /*!
   * \return a member of the compound of the given type
   * \param[in] n: member name
   */
  template<typename T>
  T extract(const std::string&) const;
  /*!
   * \return a member of the compound of the given type
   * \param[in] n: member name
   */
  template<typename T>
  T extract(const char *) const;
private:
  //! the description of the compound data type
  H5::CompType ctype;
  //! an intermediate storage for the compound data type
  std::vector<char> data;
}; // end of CompoundExtractor

template<typename T>
T CompoundExtractor::extract(const char *n) const{
  const auto i = this->ctype.getMemberIndex(n);
  const auto o = this->ctype.getMemberOffset(i);
  return *(reinterpret_cast<const T *>(this->data.data()+o));
} // end of CompoundExtractor::extract

template<typename T>
T CompoundExtractor::extract(const std::string& n) const{
  const auto i = this->ctype.getMemberIndex(n);
  const auto o = this->ctype.getMemberOffset(i);
  return *(reinterpret_cast<const T *>(this->data.data()+o));
} // end of CompoundExtractor::extract

CompoundExtractor::CompoundExtractor(const DataSet& d)
{
  const auto dtype = d.getDataType();
  if(dtype.getClass()!=H5T_COMPOUND){
    throw(std::runtime_error("CompoundExtractor: invalid data set"));
  }
  this->ctype = H5::CompType(d);
  this->data.resize(ctype.getSize());
  d.read(this->data.data(),ctype);
}

CompoundExtractor::~CompoundExtractor() = default;

【讨论】:

    猜你喜欢
    • 2018-07-13
    • 2013-01-03
    • 2017-10-02
    • 2013-12-04
    • 2011-07-14
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 2013-12-17
    相关资源
    最近更新 更多