HDF5: compound data type to write a struct containing a pointer to another struct

Viewed 575

I'm trying to write to HDF5 a struct that contains a pointer to another. Something like this:

typedef struct{
    int32_t  method;
    void*    methodParams;
    float    result;
}Measure;

typedef struct{
    int32_t    param1;
    int32_t    param2;
}OneMethod;

The following code to describe the compound data type does not work:

Measure value;
hid_t method_tid;
hid_t measure_tid;

method_tid = H5Tcreate(H5T_COMPOUND, sizeof(OneMethod));
H5Tinsert(method_tid, "P1", HOFFSET(OneMethod, param1), H5T_NATIVE_INT32);
H5Tinsert(method_tid, "P2", HOFFSET(OneMethod, param2), H5T_NATIVE_INT32);

measure_tid = H5Tcreate(H5T_COMPOUND, sizeof(Measure));
H5Tinsert(measure_tid, "Method", HOFFSET(Measure, method), H5T_NATIVE_INT32);
H5Tinsert(measure_tid, "Params", HOFFSET(Measure, methodParams), method_tid);
H5Tinsert(measure_tid, "Result", HOFFSET(Measure, result), H5T_NATIVE_FLOAT);

hsize_t dim[] = { 1 };
hid_t space = H5Screate_simple(1, dim, NULL);

hid_t dataset = H5Dcreate(objid, name, measure_tid, space, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
herr_t ret = H5Dwrite(dataset, measure_tid, H5S_ALL, H5S_ALL, H5P_DEFAULT, &value);

H5Tclose(method_tid);
H5Tclose(measure_tid);
H5Sclose(space);
H5Dclose(dataset);

the compound datatype is written but the methodParams field is missing. I guess because I'm not instructing the library to expect a pointer at its position. How shall I do it?

EDIT

Please consider that the struct is with the pointer because each method (given by the first struct's field) has different amounts and kinds of parameters. Of course a way would be to merge all the params from all the methods on the first level of the struct, which is something I would like to avoid.

1 Answers

The H5Tinsert() calls are just laying out the bytes for storage and what is actually in that struct is a pointer, not the thing pointed to. Padding aside, the memory you are sending the library consists of an int, a pointer, and a float. The library will simply try to slice and dice that memory according to what you told it about the type arrangement in the H5Tinsert() calls. It will not resolve pointers in complex data structures (people often get confused about this when they try to send multidimensional arrays built with pointers to HDF5).

The most straightforward thing to do would be to revise your structs to look something like this:

typedef struct{
    int32_t  method;
    int32_t  param1;
    int32_t  param2;
    float    result;
}hdf5_Measure;

And manually fill that, at least for HDF5 I/O.

Related