Reputation: 493
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.
Upvotes: 0
Views: 580
Reputation: 15017
I know it's been some time, but I came upon this today. Here is a proper c++ solution, not allocating additional memory, but just storing the pointer to the vectors in the vlen_t
:
// 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();
X[i].p = (void*) &jagged_array[i].front();
}
Upvotes: 1
Reputation: 493
@Lashane answered in the comments:
One should simply use
hvl_t * X = (hvl_t *)malloc(jagged_array.size() * sizeof(hvl_t))
Upvotes: 0