Search code examples
cunit-testingserializationvirtualizationfwrite

Virtualizing fopen with some malloc-ed memory instead of using a file


I have a piece of code using a FILE* file with a fwrite:

test = fwrite(&object,sizeof(object),1,file);

I want to serialize some internal data structure with an indexing structure (so, I'm using neither Google's Protobuf nor Cap'n Proto, since that is a custom data structure with some specific indexing requirements). Now, inside my project, I want to use Google Test in order to test the serialization, in order to check that what it has been serialized it could be deserialized and easily retrieved, too. In the testing phase, I want to pass to fwrite a FILE* object which is not a file, but a handler to some allocated main memory, so that no file is procuded, and that I can directly check the main memory for the results of the serialization. Is it possible to virtualize the FILE* and to write directly into the main memory? I would like to keep fwrite for writing data structures for performance reasons, without being forced to write two different methods for serialization (Sometimes i'm writing on the fly with no further memory occupation for transcoding). Thanks in advance.


Solution

  • fopencookie did the job I was looking for.

    http://man7.org/linux/man-pages/man3/fopencookie.3.html