Question

I am using an HDF5 library to read data from an HDF5 file in c++ and the call I am having problems with is the following:

status = H5Dread(
    hdf5_dataset,
    hdf5_datatype,
    hdf5_dataspace_in_memory,
    hdf5_dataspace_in_file,
    H5P_DEFAULT,
    buf
);

The last argument is supposed to be a void pointer, and I have a vector of floats that I want to be allocated, however when I try to pass the vector g++ gives me the following error:

error: cannot convert ‘std::vector<float, std::allocator<float> >’ to ‘void*’ for argument ‘6’ to ‘herr_t H5Dread(hid_t, hid_t, hid_t, hid_t, hid_t, void*)’

Is there any way that I can write directly to the vector without having to allocate the memory twice?

Was it helpful?

Solution

As std::vector guarantees the data is stored in contiguous memory, you can convert a vector to a pointer like so:

std::vector<float> myFloats;
void *ptr = static_cast<void*>(&myFloats[0]); // or &myFloats.front()

Edit: if you are writing to it without calling push_back, make sure you resize enough space first!

OTHER TIPS

Given a std::vector<float>, you can obtain a pointer to the contiguous buffer of floats thus:

std::vector<float> v;
fillMyVectorSomehow(v);

float* buffer = &v[0]; // <---

You could cast this to void* and pass it through.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top