如何将结构体导出到文件,然后对文件进行内存映射?
我有一个结构,我想导出到一个文件,然后 mmap() 该文件。一个问题是该结构有一个字符串成员变量,我不确定 mmap 将如何处理它。在这种情况下,所有这些字符串都具有相同的大小,即 8 个字符。我正在 Windows 上工作,尽管我使用 mmap( ) 函数是我在网上找到的,它应该复制 Linux mmap() 函数。
结构体本身定义为:
struct testStruct
{
string testString;
unsigned int testInt;
unsigned int tsetArr[9];
};
是否可以为对象定义 sizeof() 的返回值?
映射包含结构数据的文件是否可能?
我必须使用什么代码将结构导出到文件,然后映射它?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C++ 标准不保证
std::string
的表示形式,因此这不起作用。 std::string 可以(并且通常会)将其内容分配在堆上的任何位置,因此您将存储一个指针和一个大小成员,而不是字符串本身。不过,具有编译时常量大小的
char
数组(例如tsetArr
)应该可以工作。不。
sizeof
不是一个函数,因此您不能重载它(严格来说,它有一个值,但没有返回值因为它不会从任何地方返回;它被编译器扩展为常量)。是的,有可能,但我建议不要这样做;您的代码将不可移植,甚至可能无法移植到同一平台上的不同编译器,并且您的
struct
是一成不变的。如果您无论如何都想这样做,只需mmap
POD(纯旧数据),不带指针成员,并在您的struct
中放置一个unsigned version
成员每次更改其定义时都会增加该值。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 astsetArr
, should work, though.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).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, onlymmap
POD (plain old data) with no pointer members and put anunsigned version
member in yourstruct
that you increment every time its definition is changed.