Given the following function, I am trying to write a variable length string to an open HDF5 file. However, the H5Awrite(...)
line causes an access violation inside the HDF5 stack, which I can't see. Before I go find or build debug libraries for HDF5, I was hoping there was some obvious issue.
Also, I removed the error handling that would normally be there to make the code more simple while debugging and sharing. I inspected and verified each hid_t
is valid, and the HDF5 library has not issued any prior warnings or errors.
#include <hdf5.h>
#include <string>
void writeAttr(hid_t parent, const std::string& name, const std::string& value)
{
hid_t type = H5Tcopy(H5T_C_S1);
H5Tset_size(type, H5T_VARIABLE);
hid_t attr = H5Acreate(parent, name.c_str(), type, H5Screate(H5S_SCALAR), H5P_DEFAULT, H5P_DEFAULT);
herr_t status = H5Awrite(attr, type, value.c_str()); // <-- access violation
H5Aclose(attr);
H5Tclose(type);
}
int main()
{
const std::string filename = "D:\\test.h5";
hid_t file = H5Fcreate(filename.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
writeAttr(file, "Attribute", "Attribute value");
H5Fclose(file);
return 0;
}
I have also tried adding the following with no luck:
H5Tset_cset(type, H5T_CSET_ASCII);
H5Tset_strpad(type, H5T_STR_NULLTERM);
HDF5 library version 1.14.1
I cheated and asked one of the hdf5 maintainers who was kind enough to resolve the issue:
"Variable-length strings are a bit of a special case in HDF5. It's potentially a bit misleading due to the way the array is declared." ... "The short of it is essentially that the library expects char *
for strings and char **
for variable-length strings.".
So:
auto lvptr = value.c_str();
herr_t status = H5Awrite(attr, type, &lvptr);
Then it runs without issues.