How to export a struct to a file, and then memory map the file?
I have a str开发者_运维百科uct 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?
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.
struct testStruct
{
char testString[9];
unsigned int testInt;
unsigned int tsetArr[9];
};
精彩评论