Warm tip: This article is reproduced from serverfault.com, please click

HDF5 variable length structure, of variable length (C API)

发布于 2015-03-18 20:11:34

I'd like to write data which is contained in a STL container to a HDF5 file. From what I gathered, I need to declare a contiguous memory block and use the "hdf5.h" C API to transfer the data from the memory buffer to the disk.

For regular dataspaces, the procedure is straightforward; one only needs to create temporary arrays on the stack with new. HDF5 "understands" such memory layouts. It is a different story when one deals with irregular dataspaces, because the dedicated type hvl_t must be used.

The following snippet works but is not ISO C++(11) :

// Test data
std::vector< std::vector<int> > jagged_array(3);
jagged_array[0] = {0};
jagged_array[1] = {0, 1, 2, 3};
jagged_array[2] = {0, 1, 2};

hvl_t X[jagged_array.size()];
for (unsigned int i = 0; i < jagged_array.size(); ++i) {
    X[i].len = jagged_array[i].size();
    int * ptr = (int *) malloc (X[i].len * sizeof(int));
    for (unsigned int j = 0; j < X[i].len; ++j) {
        ptr[j] = jagged_array[i][j];
    }
    X[i].p = (void *) ptr;
}

My C is extremely rusty; this snippet is almost entirely ripped off the HDF5 example page, except for the illegal line hvl_t X[jagged_array.size()];.

How should I go about declaring an hvl_t with a size determined at runtime? It surely involves malloc, but I'm really stumped here.

Questioner
jgyou
Viewed
0
community wiki 2015-03-20 23:54:48

@Lashane answered in the comments:

One should simply use

hvl_t * X = (hvl_t *)malloc(jagged_array.size() * sizeof(hvl_t))