如何在C++中将stl::string写入HDF5文件

3
我正在 Windows 平台上使用 HDF5 CPP 库。基本上,我想要将包含 std::string 的复合数据类型写入 H5 文件。
这段代码没有出现错误,但在写入 H5 文件时会写入垃圾值。。。
各位有什么提示是有帮助的...
以下是我的代码:
#include <H5Cpp.h >
#include <vector>
#include <string>
#include <iostream>

using namespace std;
using namespace H5;


/**Compound datatype with STL Datatype*/
struct PostProcessingData
{
  std::string datatype;
};
void main()
{
    H5File file("ResultData.h5",H5F_ACC_TRUNC);
    Group grp(file.createGroup("PostProcessing"));

    PostProcessingData data;
    data.datatype = "stress:xx";

    // create spatial structure of data
    hsize_t len = 1;
    hsize_t dim[1] = {len};
    int rank = 1;
    DataSpace space(rank,dim); 

    // write required size char array
    hid_t strtype = H5Tcopy (H5T_C_S1);
    H5Tset_size (strtype, H5T_VARIABLE);

    //defining the datatype to pass HDF55
    H5::CompType mtype(sizeof(PostProcessingData));
    mtype.insertMember("Filename", HOFFSET(PostProcessingData, datatype), strtype);


    DataSet dataset =  grp.createDataSet("subc_id2",mtype,space);
    dataset.write(&data,mtype);
    space.close();
    mtype.close();
    dataset.close();
    grp.close();
    file.close();
    exit(0);
 }

有人可以帮我吗? - Shamkumar Rajput
1个回答

2
我得到了以下的解决方法,可以将一个字符串存储在HDF5中:- 我必须将std::string转换为char*指针。 对于原始数据类型,HDF5非常好。
#include "H5Cpp.h"
#include <vector>
#include <string>
#include <iostream>


using namespace std;
using namespace H5;


/**Compound datatype with STL Datatype*/
struct PostProcessingData
{
    char* datatype;
};

void main()
{
    H5File file("ResultData.h5",H5F_ACC_TRUNC);
    Group grp(file.createGroup("PostProcessing"));

    PostProcessingData data;
    std::string dt = "stress:xx";
    data.datatype = new char[dt.length()];
    data.datatype = const_cast<char*> (dt.data());

    // create spatial structure of data
    hsize_t len = 1;
    hsize_t dim[1] = {len};
    int rank = 1;
    DataSpace space(rank,dim); 

    // write required size char array
    hid_t strtype = H5Tcopy (H5T_C_S1);
    H5Tset_size (strtype, H5T_VARIABLE);

    //defining the datatype to pass HDF55
    H5::CompType mtype(sizeof(PostProcessingData));
    mtype.insertMember("Filename", HOFFSET(PostProcessingData, datatype), strtype);


    DataSet dataset =  grp.createDataSet("subc_id2",mtype,space);
    //While writing data to file it gives following error
    dataset.write(&data,mtype);
    space.close();
    mtype.close();
    dataset.close();
    grp.close();
    file.close();
    exit(0);

}

这是文件快照: 在这里输入图片描述

我看到了这篇文章,你不需要执行data.datatype = new char[dt.length()];。在你调用返回由字符串对象拥有的指针的data()之后,这会导致内存泄漏。 - Alexandre Pieroux

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