I am trying to write a HDF5 file with a structure which contains an int and a float*
typedef struct s1_t {
int a;
float *b;
} s1_t;
However,
You are right. Changing your structure to
typedef struct s1_t {
int a;
float b[ARRAY_DIM];
} s1_t;
would work, but I guess you know that.
I can see two solutions:
b_name
.b_name
#include "stdio.h"
#include "stdlib.h"
#include "hdf5.h"
#define FILE "DSwith_array_member.h5"
#define DATASETNAME "ArrayOfStructures"
#define LENGTH 10
#define RANK 1
#define ARRAY_RANK 1
#define ARRAY_DIM 3
typedef struct s1_t {
int a;
float *b;
} s1_t;
typedef struct s1_buffer_t {
int a;
hvl_t b;
} s1_buffer_t;
int main(void)
{
s1_t s1[LENGTH];
hid_t s1_tid; /* File datatype identifier */
hid_t file, dataset, space, vlen_tid; /* Handles */
hsize_t dim[] = {LENGTH}; /* Dataspace dimensions */
int i, j;
s1_buffer_t s1_buffer[LENGTH];
for (i = 0; i< LENGTH; i++) {
s1[i].a = i;
s1[i].b = (float*)calloc(ARRAY_DIM, sizeof(float));
for (j = 0; j < ARRAY_DIM; j++) {
s1[i].b[j] = i+j;
}
}
space = H5Screate_simple(RANK, dim, NULL);
file = H5Fcreate(FILE, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
vlen_tid = H5Tvlen_create(H5T_NATIVE_FLOAT);
s1_tid = H5Tcreate(H5T_COMPOUND, sizeof(s1_buffer_t));
H5Tinsert(s1_tid, "a_name", HOFFSET(s1_t, a), H5T_NATIVE_INT);
H5Tinsert(s1_tid, "b_name", HOFFSET(s1_t, b), vlen_tid);
dataset = H5Dcreate(file, DATASETNAME, s1_tid, space, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
for (i = 0; i < LENGTH; ++i)
{
s1_buffer[i].a = s1[i].a;
s1_buffer[i].b.len = ARRAY_DIM;
s1_buffer[i].b.p = s1[i].b;
}
H5Dwrite(dataset, s1_tid, H5S_ALL, H5S_ALL, H5P_DEFAULT, s1_buffer);
H5Tclose(s1_tid);
H5Tclose(vlen_tid);
H5Sclose(space);
H5Dclose(dataset);
H5Fclose(file);
return 0;
}
As you can see, you still need a temporary buffer but at least it only needs to store pointers (the b
pointers from s1
) and not arrays of size ARRAY_DIM
as would be the case with solution 1 above.