在无类型的存储空间中存储多种类型的数据 [英] storing multi-type data in untyped memory space

查看:110
本文介绍了在无类型的存储空间中存储多种类型的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码示例中,如何使* y指向偏移量4? 目前,仅指向* 0而不是* y的偏移量0.

In following code sample, how can I make *y to point to offset 4? Right now, only points to offset 0, which is for *x, not *y.

(请注意,* x和* y每个都有4个字节)

(note that *x & *y will have 4 bytes each)

unsigned char *p = new unsigned char[8];
int *x = &*(int *) p;
*x = 1;
int *y = &*(int *) p;
*y = 2;

请不要谈论struct或其他方式,它们不会帮助我.

Please dont talk about struct or other ways, they won't help me.

推荐答案

如果实际上是将多个类型存储在连续的缓冲区中,则在对齐问题上可能会感到痛苦.并非所有类型都可以在相同的内存边界上对齐:某些可能需要32位对齐,某些64位,某些128位,而这完全取决于平台.

If you are actually storing multiple types in a contiguous buffer, you might be in for a world of pain when it comes to alignment issues. Not all types can be aligned on the same memory boundaries: some might need to be 32-bit aligned, some 64-bit, some 128-bit, and this is all platform-dependent.

Some reading to get you started, but you should read a lot more including the alignment of user-defined types, and for the various compilers and operating systems you are targeting if you really want to do this the way you are doing without using a more structured approach (ex: Variant type approaches combining static and dynamic polymorphism).

实际上,如果需要这样做,您需要了解的材料与在实现自己的内存分配器时必须学习的有关数据对齐的内容非常相似(一般的内存分配器必须能够处理将多个类型存储在连续的缓冲区中),因此搜索相似的主题可能会为您提供所需的信息.我不禁要说,这个低级的问题可能会给您和任何同事带来比任何人都应有的悲痛得多.

In fact, the kind of material you need to understand if you want to do this is quite similar to what you have to learn about data alignment when implementing your own memory allocator (a general memory allocator has to deal with being able to store multiple types in contiguous buffers), so searching for similar topics may give you what you need. I can't help but say that this low-level problem may give you and any co-workers a lot more grief than anyone should ever deserve.

您需要知道什么类型需要与什么边界(字节,字,双字,四字)对齐.它也有所不同.例如,您不必存储未在字边界上对齐的int.在某些系统上,这可能会因未对齐的动作而导致巨大的性能损失,甚至使程序崩溃.这也是为什么结构通常在内部填充以确保所有数据正确对齐的原因.

You need to know what types need to be aligned to what boundaries (byte, word, doubleword, quadword). It varies as well. You can't necesarily store an int that isn't aligned on word boundaries, for example. On some systems this might take a huge performance penalty for unaligned moves or even crash your program. This is also why structs typically have padding inside to make sure all data is aligned correctly.

但是,对于您的直接示例,它没有混合类型(只是整数):

However, for your immediate example which isn't mixing types (just integers):

unsigned char *p = new unsigned char[sizeof(int) * 2];
int *x = &*(int *) p;
*x = 1;

// advance your unsigned char* pointer by the size of x
p += sizeof x; // or sizeof(int)

int *y = &*(int *) p;
*y = 2;

这篇关于在无类型的存储空间中存储多种类型的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆