Search code examples
filestreamvoid

c++ how to store a void* in a file in binary mode


i have the following function that stores 2 different types of data in a std::vector<unsigned char> called data:

void vertexBufferObject::addData(void* ptrData, unsigned int uiDataSize)
{
    //data is a std::vector<unsigned char>
    data.insert(data.end(), (char*)ptrData, (char*)ptrData+uiDataSize);
    iCurrentSize += uiDataSize;
}

now.. once the vector is filled, i get a void* to the std::vector raw data:

void* vertexBufferObject::getDataPointer()
{
    return (void*)data[0];
}

i need to write a file with this data (getDataPointer()) in binary mode. How can i do that?:

//im trying this
void* result = getDataPointer();

file.write(reinterpret_cast<const char*>(&result), iCurrentSize );

and then.. how can i recover it safely (using read()) and store again in a std::vector<unsigned char>?

for Example:

std::vector<unsigned char> retrievePointerData;

//here im trying to get the previous saved void* in my std::vector<unsigned char>
file.fread(reinterpret_cast<char*>(&retrievePointerData), iCurrentSize );

Thanks a lot!


Solution

  • Ok, I think I get it now. So, I think getDataPointer() should be:

    void* vertexBufferObject::getDataPointer()
    {
        return (void*)&data[0];
    }
    

    i.e. return a pointer to the start of the data, not a pointer with the value of whatever the first byte of data happens to be.

    Then I think your reinterpret cast should be:

    file.write(reinterpret_cast<const char*>(result), iCurrentSize );
    

    I.e. cast the void pointer to a const char* pointer. Not the address of the void pointer - that gives you a pointer to a pointer.

    As to reading it in, you need to know the size somehow before you begin - perhaps writing it first as a fixed size int to the start of the file? Anyhow, you probably just need to resize() the vector to the known size, and read in the data:

    // We assume here that iCurrentSize is actually valid.
    std::vector<unsigned char> retrievePointerData;
    retrievePointerData.resize(iCurrentSize);
    file.fread(reinterpret_cast<char*>(&retrievePointerData[0]), iCurrentSize );
    

    I must admit, I usually use iostreams for file IO in c++, so I'm not too familar with your file.write/file.fread calls.

    Also, you may want to consider not bothering with the reinterpret cast at all, and dropping the void* completely. If you just passed around unsigned char* (or better yet, typedef it to BYTE* like Win32 does) then all your types will just work with the file IO calls.