C++ HDF5 提取复合数据类型的一个成员
C++ HDF5 extract one member of a compound data type
我正在编写一个 c++ 库,用于读取另一个库生成的 hdf5 文件。
这些hdf5文件包含许多具有各种复合数据类型的复合数据集。我希望将每个复合数据类型转换为C++结构。
对于字符串(可变长度或固定大小的字符数组),我想在C++结构中使用 std::string。
目前,我使用中间 C 结构(使用 char*
或char[]
变量),然后将其转换为最终的 C++ 结构。但是,这会导致大量样板代码。
如果我可以按成员提取数据,我可以执行以下操作:
std::string name = extract<std::string>(d,"name");
其中 d 是复合数据集。
可能吗
我找到了一个可行的解决方案。我把它贴在这里,也许有人会发现它很有用。这个想法是创建一个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;
相关文章:
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 无法将指向类的成员函数的函数指针作为参数传递给同一类的另一个成员函数
- 使用只有一个成员的工会的目的是什么?
- 访问从联合与另一个成员集复制的联合中的一个成员是否未定义或未指定?
- std::mutex作为一个成员变量对多个线程来说是安全的吗
- 使用线程从另一个成员函数调用一个Member函数
- 如何通过指针将模板成员函数传递给另一个成员函数
- 只有一个成员的匿名联盟
- 复制一个对象并使两者共享一个成员变量 (C++)
- 初始化指针或引用成员变量以指向另一个成员
- 在另一个成员函数中调用成员函数时'int'之前的预期主表达式
- C 将成员函数作为参数传递给另一个成员函数
- 将结构编写为二进制,其中一个成员是字符串
- 如何在另一个成员函数中修改具有常量返回类型的成员函数的返回值
- 从其后声明的另一个成员数据初始化成员数据是否为未定义行为
- 如何使一个成员变量等于在main()中设置的另一个成员变量
- 在另一个成员中动态添加类成员
- 在对结构数组的一个成员进行排序后,移动其成员的其余部分
- 将类成员函数作为参数从同一类的另一个成员函数传递