如何最佳地将一个std::vector < std::string > 容器写入HDF5数据集?

15

给定一个字符串向量,将它们写入HDF5数据集的最佳方式是什么?目前我正在做以下操作:

  const unsigned int MaxStrLength = 512;

  struct TempContainer {
    char string[MaxStrLength];
  };

  void writeVector (hid_t group, std::vector<std::string> const & v)
  {
    //
    // Firstly copy the contents of the vector into a temporary container
    std::vector<TempContainer> tc;
    for (std::vector<std::string>::const_iterator i = v.begin ()
                                              , end = v.end ()
      ; i != end
      ; ++i)
    {
      TempContainer t;
      strncpy (t.string, i->c_str (), MaxStrLength);
      tc.push_back (t);
    }


    //
    // Write the temporary container to a dataset
    hsize_t     dims[] = { tc.size () } ;
    hid_t dataspace = H5Screate_simple(sizeof(dims)/sizeof(*dims)
                               , dims
                               , NULL);

    hid_t strtype = H5Tcopy (H5T_C_S1);
    H5Tset_size (strtype, MaxStrLength);

    hid_t datatype = H5Tcreate (H5T_COMPOUND, sizeof (TempConainer));
    H5Tinsert (datatype
      , "string"
      , HOFFSET(TempContainer, string)
      , strtype);

    hid_t dataset = H5Dcreate1 (group
                          , "files"
                          , datatype
                          , dataspace
                          , H5P_DEFAULT);

    H5Dwrite (dataset, datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, &tc[0] );

    H5Dclose (dataset);
    H5Sclose (dataspace);
    H5Tclose (strtype);
    H5Tclose (datatype);
}

至少,我希望改变以上内容,使其满足以下要求:

  1. 使用可变长度字符串
  2. 不需要临时容器

对于数据存储方式,我没有限制,因此,如果有更好的方法,它不必是一个COMPOUND数据类型。

编辑:为了缩小问题范围,我相对熟悉在C++端处理数据,而HDF5方面是我最需要帮助的地方。

感谢您的帮助。

9个回答

10

[非常感谢 dirkgently 在回答中提供的帮助。]

要在HDF5中编写变长字符串,请使用以下方法:

// Create the datatype as follows
hid_t datatype = H5Tcopy (H5T_C_S1);
H5Tset_size (datatype, H5T_VARIABLE);

// 
// Pass the string to be written to H5Dwrite
// using the address of the pointer!
const char * s = v.c_str ();
H5Dwrite (dataset
  , datatype
  , H5S_ALL
  , H5S_ALL
  , H5P_DEFAULT
  , &s );

编写容器的一种解决方案是逐个编写每个元素。这可以通过使用超级平板来实现。

例如:

class WriteString
{
public:
  WriteString (hid_t dataset, hid_t datatype
      , hid_t dataspace, hid_t memspace)
    : m_dataset (dataset), m_datatype (datatype)
    , m_dataspace (dataspace), m_memspace (memspace)
    , m_pos () {}

private:
  hid_t m_dataset;
  hid_t m_datatype;
  hid_t m_dataspace;
  hid_t m_memspace;
  int m_pos;

//...

public:
  void operator ()(std::vector<std::string>::value_type const & v)
  {
    // Select the file position, 1 record at position 'pos'
    hsize_t count[] = { 1 } ;
    hsize_t offset[] = { m_pos++ } ;
    H5Sselect_hyperslab( m_dataspace
      , H5S_SELECT_SET
      , offset
      , NULL
      , count
      , NULL );

    const char * s = v.c_str ();
    H5Dwrite (m_dataset
      , m_datatype
      , m_memspace
      , m_dataspace
      , H5P_DEFAULT
      , &s );
    }    
};

// ...

void writeVector (hid_t group, std::vector<std::string> const & v)
{
  hsize_t     dims[] = { m_files.size ()  } ;
  hid_t dataspace = H5Screate_simple(sizeof(dims)/sizeof(*dims)
                                    , dims, NULL);

  dims[0] = 1;
  hid_t memspace = H5Screate_simple(sizeof(dims)/sizeof(*dims)
                                    , dims, NULL);

  hid_t datatype = H5Tcopy (H5T_C_S1);
  H5Tset_size (datatype, H5T_VARIABLE);

  hid_t dataset = H5Dcreate1 (group, "files", datatype
                             , dataspace, H5P_DEFAULT);

  // 
  // Select the "memory" to be written out - just 1 record.
  hsize_t offset[] = { 0 } ;
  hsize_t count[] = { 1 } ;
  H5Sselect_hyperslab( memspace, H5S_SELECT_SET, offset
                     , NULL, count, NULL );

  std::for_each (v.begin ()
      , v.end ()
      , WriteStrings (dataset, datatype, dataspace, memspace));

  H5Dclose (dataset);
  H5Sclose (dataspace);
  H5Sclose (memspace);
  H5Tclose (datatype);
}      

你知道吗?HDF5是我一直想要阅读和编写的东西之一。但是,由于拖延症是我的名字,所以这并没有实现。多亏了你,我决定这次更加专注地尝试。如果可能的话,我非常非常有兴趣知道你在哪里使用它。 - dirkgently
我们正在考虑更改静态分析工具存储其分析数据的方式。该数据将包含树状结构(作用域、类型等)和诊断列表。目前,我只是在评估HDF5处理不同类型数据的能力。 - Richard Corden
这个问题(我所提出的)概述了我们正在评估的功能的类型: https://dev59.com/A3RB5IYBdhLWcg3wtJGF - Richard Corden

5
这里是使用HDF5 c++ API编写变长字符串向量的可用代码示例。
我结合了其他帖子中的一些建议:
1. 使用H5T_C_S1和H5T_VARIABLE 2. 使用string::c_str()获取指向字符串的指针 3. 将指针放入char*的vector中并传递给HDF5 API
不必创建昂贵的字符串副本(例如使用strdup())。c_str()返回指向基础字符串的以null终止数据的指针。这正是函数的设计目的。当然,具有嵌入空值的字符串将无法使用此方法...
std::vector保证具有连续的底层存储,因此使用vector和vector::data()等同于使用原始数组,但比笨拙、老式的C方式更加整洁和安全。
#include "H5Cpp.h"
void write_hdf5(H5::H5File file, const std::string& data_set_name,
                const std::vector<std::string>& strings )
{
    H5::Exception::dontPrint();

    try
    {
        // HDF5 only understands vector of char* :-(
        std::vector<const char*> arr_c_str;
        for (unsigned ii = 0; ii < strings.size(); ++ii) 
            arr_c_str.push_back(strings[ii].c_str());

        //
        //  one dimension
        // 
        hsize_t     str_dimsf[1] {arr_c_str.size()};
        H5::DataSpace   dataspace(1, str_dimsf);

        // Variable length string
        H5::StrType datatype(H5::PredType::C_S1, H5T_VARIABLE); 
        H5::DataSet str_dataset = file.createDataSet(data_set_name, datatype, dataspace);

        str_dataset.write(arr_c_str.data(), datatype);
    }
    catch (H5::Exception& err)
    {
        throw std::runtime_error(string("HDF5 Error in " ) 
                                    + err.getFuncName()
                                    + ": "
                                    + err.getDetailMsg());


    }
}

不错!但是如何将其从文件中读取到 std::vector<std::string> 中呢? - Walter
这个程序在哪个操作系统上可以运行?因为看起来它会在很多机器上导致段错误,或者破坏你的数据。我有所怀疑,因为我之前做过类似的事情,在Linux上可以工作但在OSX上失败了。 - Shep

1
我来晚了,但基于关于段错误的评论,我修改了Leo Goodstadt的答案。我在Linux上,但我没有遇到这样的问题。我编写了两个函数,一个用于将std::string向量写入打开的H5File中给定名称的数据集,另一个用于将结果数据集读回std::string向量中。请注意,可能会有一些类型之间不必要的复制,可以进行更多的优化。以下是可工作的编写和读取代码:
void write_varnames( const std::string& dsetname, const std::vector<std::string>& strings, H5::H5File& f)
  {
    H5::Exception::dontPrint();

    try
      {
        // HDF5 only understands vector of char* :-(
        std::vector<const char*> arr_c_str;
        for (size_t ii = 0; ii < strings.size(); ++ii)
      {
        arr_c_str.push_back(strings[ii].c_str());
      }

        //
        //  one dimension
        // 
        hsize_t     str_dimsf[1] {arr_c_str.size()};
        H5::DataSpace   dataspace(1, str_dimsf);

        // Variable length string
        H5::StrType datatype(H5::PredType::C_S1, H5T_VARIABLE); 
        H5::DataSet str_dataset = f.createDataSet(dsetname, datatype, dataspace);

        str_dataset.write(arr_c_str.data(), datatype);
      }
    catch (H5::Exception& err)
      {
        throw std::runtime_error(std::string("HDF5 Error in ")  
                 + err.getFuncName()
                 + ": "
                 + err.getDetailMsg());


      }
  }

并阅读:

std::vector<std::string> read_string_dset( const std::string& dsname, H5::H5File& f )
  {
    H5::DataSet cdataset = f.openDataSet( dsname );


    H5::DataSpace space = cdataset.getSpace();

    int rank = space.getSimpleExtentNdims();

    hsize_t dims_out[1];

    int ndims = space.getSimpleExtentDims( dims_out, NULL);

    size_t length = dims_out[0];

    std::vector<const char*> tmpvect( length, NULL );

    fprintf(stdout, "In read STRING dataset, got number of strings: [%ld]\n", length );

    std::vector<std::string> strs(length);
    H5::StrType datatype(H5::PredType::C_S1, H5T_VARIABLE); 
    cdataset.read( tmpvect.data(), datatype);

    for(size_t x=0; x<tmpvect.size(); ++x)
      {
        fprintf(stdout, "GOT STRING [%s]\n", tmpvect[x] );
        strs[x] = tmpvect[x];
      }

    return strs;
  }

1
如果你想要更清晰的代码:我建议你创建一个函数对象,它将接受一个字符串并将其保存到HDF5容器中(以所需的模式)。Richard,我使用了错误的算法,请重新检查!
std::for_each(v.begin(), v.end(), write_hdf5);

struct hdf5 : public std::unary_function<std::string, void> {
    hdf5() : _dataset(...) {} // initialize the HDF5 db
    ~hdf5() : _dataset(...) {} // close the the HDF5 db
    void operator(std::string& s) {
            // append 
            // use s.c_str() ?
    }
};

这有助于开始吗?


我对HDF5非常陌生,所以我不知道在你的“// append”处需要写什么。 - Richard Corden
我只是听说过HDF5。我的意思是在注释//将临时容器写入数据集下面追加任何你正在做的事情。 - dirkgently
所以我们现在正在问同样的问题!;) 我找到的所有H5Dwrite的示例似乎都是一次性写入整个“数据集”,而不是逐个条目写入。 - Richard Corden
从我在这里看到的--http://www.hdfgroup.org/HDF5/doc/RM/RM_H5D.html#Dataset-Write--来看,这种方法应该是可行的。 - dirkgently
'HDFwrite()一次写入部分数据集。' - dirkgently
显示剩余9条评论

1
我遇到了类似的问题,但需要将字符串向量存储为属性。属性的棘手之处在于我们无法使用高级数据空间功能(至少不能使用C++ API)。
但无论哪种情况,如果将字符串向量输入到数据集的单个条目中可能很有用(例如,如果您始终希望将它们一起读取)。在这种情况下,所有的魔力都来自类型,而不是数据空间本身。
基本上有四个步骤:
  1. 创建一个指向字符串的vector<const char*>
  2. 创建一个指向向量并包含其长度的hvl_t结构。
  3. 创建数据类型。这是一个封装了(可变长度)H5::StrTypeH5::VarLenType
  4. hvl_t类型写入数据集。
这种方法的真正好处是你将整个条目塞进了HDF5认为是标量值的东西中。这意味着将其作为属性(而不是数据集)非常简单。
无论您选择这个解决方案还是每个字符串在其自己的数据集条目中的解决方案,可能也取决于所需的性能:如果您正在寻找对特定字符串的随机访问,则最好将字符串写入数据集中以便可以进行索引。如果您总是将它们一起读出来,那么这个解决方案可能同样有效。

以下是使用C ++ API和简单标量数据集执行此操作的简短示例:

#include <vector>
#include <string>
#include "H5Cpp.h"

int main(int argc, char* argv[]) {
  // Part 0: make up some data
  std::vector<std::string> strings;
  for (int iii = 0; iii < 10; iii++) {
    strings.push_back("this is " + std::to_string(iii));
  }

  // Part 1: grab pointers to the chars
  std::vector<const char*> chars;
  for (const auto& str: strings) {
    chars.push_back(str.data());
  }

  // Part 2: create the variable length type
  hvl_t hdf_buffer;
  hdf_buffer.p = chars.data();
  hdf_buffer.len = chars.size();

  // Part 3: create the type
  auto s_type = H5::StrType(H5::PredType::C_S1, H5T_VARIABLE);
  s_type.setCset(H5T_CSET_UTF8); // just for fun, you don't need this
  auto svec_type = H5::VarLenType(&s_type);

  // Part 4: write the output to a scalar dataset
  H5::H5File out_file("vtest.h5", H5F_ACC_EXCL);
  H5::DataSet dataset(
    out_file.createDataSet("the_ds", svec_type, H5S_SCALAR));
  dataset.write(&hdf_buffer, svec_type);

  return 0;
}

1

如您所知,HDF5文件只接受char*格式的数据,它是一个地址。因此最自然的方法是动态创建连续的地址(给定空间大小),并将向量的值复制到其中。

char* strs = NULL;
strs = (char*)malloc(date.size() * (date[0].size() + 1) * (char)sizeof(char));

for (int i = 0; i < date.size(); i++) {
    string s = date[i];
    strcpy(strs + i * (date[0].size() + 1), date[i].c_str());
}

完整代码如下:
 bool writeString(hid_t file_id, vector<string>& date, string dateSetName) {
    hid_t dataset_id, dataspace_id;  /* identifiers */
    herr_t status;
    hid_t dtype;
    size_t size;
    hsize_t dims[1] = { date.size() };
    dataspace_id = H5Screate_simple(1, dims, NULL);


    dtype = H5Tcopy(H5T_C_S1);
    size = (date[0].size() + 1) * sizeof(char);
    status = H5Tset_size(dtype, size);

    char* strs = NULL;
    strs = (char*)malloc(date.size() * (date[0].size() + 1) * (char)sizeof(char));

    for (int i = 0; i < date.size(); i++) {
        string s = date[i];
        strcpy(strs + i * (date[0].size() + 1), date[i].c_str());
        
    }

    dataset_id = H5Dcreate(file_id, dateSetName.c_str(), dtype, dataspace_id, H5P_DEFAULT,
        H5P_DEFAULT, H5P_DEFAULT);

    status = H5Dwrite(dataset_id, dtype, H5S_ALL, H5S_ALL, H5P_DEFAULT, strs);

    status = H5Dclose(dataset_id);
    status = H5Sclose(dataspace_id);
    status = H5Tclose(dtype);
    free(strs);
    return true;
}

不要忘记释放指针。


0
为了能够阅读std::vector<std::string>,我在这里发布了我的解决方案,基于Leo在https://dev59.com/SXRB5IYBdhLWcg3wl4EP#15220532中的提示。
我混合使用了C和C++ API。请随意编辑并简化它。
请注意,当您调用read时,HDF5 API返回一个char*指针列表。这些char*指针必须在使用后释放,否则会出现内存泄漏。
使用示例
H5::Attribute Foo = file.openAttribute("Foo");
std::vector<std::string> foos
Foo >> foos;

这是代码

  const H5::Attribute& operator>>(const H5::Attribute& attr0, std::vector<std::string>& array)
  {
      H5::Exception::dontPrint();

      try
      {
          hid_t attr = attr0.getId();

          hid_t atype = H5Aget_type(attr);
          hid_t aspace = H5Aget_space(attr);
          int rank = H5Sget_simple_extent_ndims(aspace);
          if (rank != 1) throw PBException("Attribute " + attr0.getName() + " is not a string array");

          hsize_t sdim[1];
          herr_t ret = H5Sget_simple_extent_dims(aspace, sdim, NULL);
          size_t size = H5Tget_size (atype);
          if (size != sizeof(void*))
          {
              throw PBException("Internal inconsistency. Expected pointer size element");
          }

          // HDF5 only understands vector of char* :-(
          std::vector<char*> arr_c_str(sdim[0]);

          H5::StrType stringType(H5::PredType::C_S1, H5T_VARIABLE);
          attr0.read(stringType, arr_c_str.data());
          array.resize(sdim[0]);
          for(int i=0;i<sdim[0];i++)
          {
              // std::cout << i << "=" << arr_c_str[i] << std::endl;
              array[i] = arr_c_str[i];
              free(arr_c_str[i]);
          }

      }
      catch (H5::Exception& err)
      {
          throw std::runtime_error(string("HDF5 Error in " )
                                    + err.getFuncName()
                                    + ": "
                                    + err.getDetailMsg());


      }

      return attr0;
  }

0

你可以使用一个简单的std::vector代替TempContainer(你也可以将其模板化以匹配T -> basic_string。像这样:

#include <algorithm>
#include <vector>
#include <string>
#include <functional>

class StringToVector
  : std::unary_function<std::vector<char>, std::string> {
public:
  std::vector<char> operator()(const std::string &s) const {
    // assumes you want a NUL-terminated string
    const char* str = s.c_str();
    std::size_t size = 1 + std::strlen(str);
    // s.size() != strlen(s.c_str())
    std::vector<char> buf(&str[0], &str[size]);
    return buf;
  }
};

void conv(const std::vector<std::string> &vi,
          std::vector<std::vector<char> > &vo)
{
  // assert vo.size() == vi.size()
  std::transform(vi.begin(), vi.end(),
                 vo.begin(),
                 StringToVector());
}

-1

我不了解HDF5,但是你可以使用

struct TempContainer {
    char* string;
};

然后以这种方式复制字符串:

TempContainer t;
t.string = strdup(i->c_str());
tc.push_back (t);

这将分配一个确切大小的字符串,并且在插入或从容器中读取时也会有很大改进(在您的示例中,有一个复制的数组,在这种情况下只有一个指针)。您还可以使用std::vector:

std::vector<char *> tc;
...
tc.push_back(strdup(i->c_str());

当然。理想情况下,我根本不需要临时容器。这段代码的缺点是需要显式释放内存。 - Richard Corden

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接