문제

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?

도움이 되었습니까?

해결책

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!

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top