读取共享内存中的不同数据类型
我想在运行 DLL 的不同进程之间共享一些内存。因此,我通过 HANDLE hSharedFile = CreateFileMapping(...)
创建一个内存映射文件,然后 LPBYTE hSharedView = MapViewOfFile(...)
和 LPBYTE aux = hSharedView
现在我想读取一个 bool
、一个 int
、一个 float
和一个 char
辅助阵列。读取 bool
和 char
很容易。但是我该如何读取 int
或 float
呢?请注意,int
或 float
可以从位置 9 开始,例如不能被 4 整除的位置。
我知道您可以读取 char[4],然后将其
memcpy
转换为 float
或 int
。但我真的需要这个速度非常快。我想知道是否可以用指针做一些事情?
提前致谢
I want to share some memory between different processes running a DLL. Therefore i create a memory-mapped-file by HANDLE hSharedFile = CreateFileMapping(...)
then LPBYTE hSharedView = MapViewOfFile(...)
and LPBYTE aux = hSharedView
Now I want to read a bool
, a int
, a float
and a char
from the aux array. Reading a bool
and char
is easy. But how would I go around reading a int
or float
? Notice that the int
or float
could start at position 9 e.g. a position that is not dividable by 4.
I know you can read a char[4]
and then memcpy
it into a float
or int
. But i really need this to be very fast. I am wondering if it is possible to do something with pointers?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
例如,如果您知道数组元素 aux[13..16] 包含一个浮点数,那么您可以通过多种方式访问该浮点数:
If you know, for instance, that array elements aux[13..16] contain a float, then you can access this float in several ways:
在偏移量 9 处获取
int
并没有什么问题:这种“未对齐”访问可能会带来非常小的性能损失,但它仍然可以正常工作,并且您有可能注意到任何差异都很微小。
There is nothing wrong with grabbing an
int
at offset 9:There might be a really tiny performance penalty for this "unaligned" access, but it will still work correctly, and the chances of you noticing any differences are slim.
首先,我认为你应该衡量。我可以想到三个选项:
缓冲区中未对齐的内存可以正常工作,只是比对齐的速度慢。那有多慢,这对你来说重要吗?测量一下就知道了。
复制到缓冲区将牺牲较慢的未对齐访问以换取额外的复制操作。测量会告诉你是否值得。
如果使用未对齐的内存对您来说太慢,并且您不想复制数据(可能是因为性能成本),那么您可以通过浪费一些内存空间并增加程序复杂性来加快速度。不要盲目使用映射内存:将“基”指针向上舍入为合适的值(例如 8 字节),并且仅以该“基”值的 8 字节增量进行读/写。这将确保您的所有访问都是一致的。
但在陷入所有这些麻烦之前,请先衡量一下。
First of all, I think you should measure. There are three options you can go with that I can think of:
memcpy
into buffersUnaligned memory will work fine, it will just be slower than aligned. How slower is that, and does it matter to you? Measure to find out.
Copying into a buffer will trade off the slower unaligned accesses for additional copy operations. Measuring will tell you if it's worth it.
If using unaligned memory is too slow for you and you don't want to copy data around (perhaps because of the performance cost), then you can possibly do faster by wasting some memory space and increasing your program complexity. Don't use the mapped memory blindly: round your "base" pointer upwards to a suitable value (e.g. 8 bytes) and only do reads/writes at 8-byte increments of this "base" value. This will ensure that all your accesses will be aligned.
But do measure before you go into all this trouble.