我想把多个二维char数组写入一个HDF5数据集。在下面的代码中,一个结构中有两个数组,我把(std::copy) "hello "s放到一个数组中()name
)和 "嗨 "的对方(nicknams
). 我以为结果会是这样的。
(b'hello', b'hey')
(b'hello', b'hey')
(b'hello', b'hey')
(b'hello', b'hey')
但当我实际运行这段代码时,结果是这样的:
(b'hello', b'hey')
(b'(\xae\nVD\xae\nV\xff\xff', b'\xdc\x82\nV\x12\xd2\xfcv\x8f\x01')
(b'\x04', b'\x01')
(b'$\xf8O', b'9\x08\xd2\xd5\xb4\xf8O')]
由于第一行看起来很好,我猜测在向数据集写入数组时,空字符有问题。我查了一下官方网页上的示例代码(https:/support.hdfgroup.orgHDF5examples。),但我还是不明白这个问题从何而来。我想知道问题出在哪里,如何解决这个问题。
#include "pch.h"
#include <iostream>
#include "H5Cpp.h"
using namespace H5;
const H5std_string MEMBER1("name");
const H5std_string MEMBER2("nickname");
struct newStruct1 {
char name[4][10]{};
char nickname[4][10]{};
};
void struct_to_dataset(newStruct1 *ptr_struct)
{
H5File file("file.h5", H5F_ACC_TRUNC);
hid_t dtype_str = H5Tcopy(H5T_C_S1);
size_t size = 10 * sizeof(char);
H5Tset_size(dtype_str, size);
hsize_t dim[] = { 4 };
DataSpace space(1, dim);
CompType mtype1(sizeof(newStruct1));
mtype1.insertMember(MEMBER1, HOFFSET(newStruct1, name), dtype_str);
mtype1.insertMember(MEMBER2, HOFFSET(newStruct1, nickname), dtype_str);
DataSet dataset = file.createDataSet("dset", mtype1, space);
dataset.write(ptr_struct, mtype1);
}
int main()
{
newStruct1 struct01;
newStruct1 *ptr01 = &struct01;
char word1[10] = { "hello" };
char word2[10] = { "hey" };
for (int i = 0; i < 4; i++) {
std::copy(word1, word1 + 10, ptr01->name[i]);
std::copy(word2, word2 + 10, ptr01->nickname[i]);
}
struct_to_dataset(ptr01);
}
请看一下 HDFql 因为它可以减轻你处理HDF5复合数据集的低级细节。使用C++中的HDFql,你的问题可以得到如下解决。
// define structure
struct data
{
char name[10];
char nickname[10];
};
// declare variables
char script[1024];
struct data values[4];
int i;
// create an HDF5 file named "file.h5"
HDFql::execute("CREATE FILE file.h5");
// use (i.e. open) HDF5 file "file.h5"
HDFql::execute("USE FILE file.h5");
// create a dataset named "dset" of data type compound of one dimension (size 4) composed of two members (name and nickname)
HDFql::execute("CREATE DATASET dset AS COMPOUND(name AS CHAR(10), nickname AS CHAR(10))(4)");
// populate variable "values"
for(i = 0; i < 4; i++)
{
memcpy(values[i].name, "hello\0\0\0\0\0", 10);
memcpy(values[i].nickname, "hey\0\0\0\0\0\0\0", 10);
}
// insert (i.e. write) values from variable "values" into dataset "dset"
sprintf(script, "INSERT INTO dset VALUES FROM MEMORY %d", HDFql::variableTransientRegister(values));
HDFql::execute(script);
关于如何使用HDFql的更多细节和例子可以在以下文章中找到 参考手册.