Question

I have a struct that I'd like to export to a file, and then mmap() that file. One issue is that the struct has a member variable that is a string, and I'm not sure how mmap would handle that. In this case all of these strings are of identical size, 8 characters. I'm working on Windows, although I'm using an mmap() function I found online which is supposed to replicate the Linux mmap() function.

The struct itself is defined as:

struct testStruct
{
    string testString;
    unsigned int testInt;
    unsigned int tsetArr[9];
};

Is it possible to define the return value of sizeof() for an object?

Would mmapping a file which contains struct data be possible?

What code would I have to use to export the struct to a file, and then mmap it?

Was it helpful?

Solution

The representation of std::string is not guaranteed by the C++ standard, so this won't work. std::string may (and commonly will) allocate its contents anywhere on the heap, so you'll be storing a pointer and a size member, rather than the string itself.

A char array with compile-time constant size, such as tsetArr, should work, though.

Is it possible to define the return value of sizeof() for an object?

No. sizeof is not a function, so you can't overload it (and strictly, it has a value, but not a return value since it doesn't return from anywhere; it's expanded to a constant by the compiler).

Would mmapping a file which contains struct data be possible?

Possible, yes, but I advise against it; your code will not be portable, perhaps not even to different compilers on the same platform, and your struct is cast in stone. If you want to do so anyway, only mmap POD (plain old data) with no pointer members and put an unsigned version member in your struct that you increment every time its definition is changed.

OTHER TIPS

struct testStruct
{
    char testString[9];
    unsigned int testInt;
    unsigned int tsetArr[9];
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top