简体   繁体   中英

C++ void pointer

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 float s thus:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM