This example shows how to make your own C++ type HDF5 serializable.
We first define a class foo
that we want to write/read to/from HDF5.
The most important functions are h5_write
and h5_read
. They are called by the generic h5::write and h5::read implementations using argument-dependent lookup (ADL).
The hdf5_format
function is optional and can be used to attach a string attribute to foo
objects. When reading from HDF5, it allows us to verify that data that we are reading is actually of type foo
.
In main()
, we simply create an HDF5 file, write an object of type foo
, read the same object from the file and output the result to stdout.
#include <iostream>
#include <string>
class foo {
private:
int i;
double d;
std::string s;
public:
foo() = default;
foo(int i, double d, std::string s) : i(i), d(d), s(s) {}
void print() const { std::cout << i << " " << d << " " << s << std::endl; }
static std::string hdf5_format() { return "foo";}
}
}
};
int main() {
h5::write(file,
"myfoo", foo(1, 2.2,
"three"));
foo f;
f.print();
}
A handle to an HDF5 file.
A handle to an HDF5 group.
group create_group(std::string const &key, bool delete_if_exists=true) const
Create a subgroup with the given key in the group.
group open_group(std::string const &key) const
Open a subgroup with the given key in the group.
T h5_read(group g, std::string const &key)
Generic implementation for reading from an HDF5 dataset/subgroup.
T read(group g, std::string const &key)
Generic implementation for reading from an HDF5 dataset/subgroup.
void write(group g, std::string const &key, T const &x, auto const &...args)
Generic implementation for writing a variable to an HDF5 dataset/subgroup.
void h5_write(group g, std::string const &name, T const &x) H5_REQUIRES(std
Write a scalar to an HDF5 dataset.
Includes all relevant h5 headers.
Output:
Contents of foo.h5
:
HDF5 "foo.h5" {
GROUP "/" {
GROUP "myfoo" {
ATTRIBUTE "Format" {
DATATYPE H5T_STRING {
STRSIZE H5T_VARIABLE;
STRPAD H5T_STR_NULLTERM;
CSET H5T_CSET_UTF8;
CTYPE H5T_C_S1;
}
DATASPACE SCALAR
DATA {
(0): "foo"
}
}
DATASET "d" {
DATATYPE H5T_IEEE_F64LE
DATASPACE SCALAR
DATA {
(0): 2.2
}
}
DATASET "i" {
DATATYPE H5T_STD_I32LE
DATASPACE SCALAR
DATA {
(0): 1
}
}
DATASET "s" {
DATATYPE H5T_STRING {
STRSIZE H5T_VARIABLE;
STRPAD H5T_STR_NULLTERM;
CSET H5T_CSET_UTF8;
CTYPE H5T_C_S1;
}
DATASPACE SCALAR
DATA {
(0): "three"
}
}
}
}
}