将复杂结构写入内存映射文件

编程入门 行业动态 更新时间:2024-10-24 04:41:45
本文介绍了将复杂结构写入内存映射文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我尝试将以下结构写入内存映射文件,但数组仍然有问题(写入时抛出异常,结构不能包含引用)

I try to write following struct to a memory mapped file, but I still have problem with the array (writing throws exception that the struct can not contain reference)

[StructLayout(LayoutKind.Explicit)] struct IndexEntry { [FieldOffset(0)] public byte key; [FieldOffset(4)] public int lastValueIdx; [FieldOffset(8)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Constants.PART_ENTRY_SIZE)] public long[] values; }

我用这个电话来写作:

UnmanagedMemoryAccessor.Write<IndexEntry>(0, ref entry);

你能告诉我,我做错了什么吗?谢谢

Can you please tell me, what am I doing wrong? Thx

推荐答案

解决方案是使用固定大小的数组和不安全的代码.所以结构应该是这样的:

The solution of this is using the fixed size array and unsafe code. So the struct should look like this:

[StructLayout(LayoutKind.Explicit)] unsafe struct IndexEntry { [FieldOffset(0)] public byte key; [FieldOffset(1)] public int lastValueIdx; [FieldOffset(5)] [MarshalAs(UnmanagedType.ByValArray, SizeConst = Constants.PART_ENTRY_SIZE)] public fixed long values[Constants.PART_ENTRY_SIZE]; }

请注意,必须使用/unasfe"选项编译程序(或包含该结构的单个项目),然后必须像这样访问数组:

Note that the program (or a single project containing that struct) must be compiled with the "/unasfe" option and the array must be then accessed like this:

fixed(long* arr = this.values) { // Setting value arr[index] = value; } unsafe { // Getting value x = obj.values[index]; }

然后 UnmanagedMemoryAccessor.Write(...) 和 UnmanagedMemoryAccessor.Read(...) 函数完美运行.

Then the UnmanagedMemoryAccessor.Write<T>(...) and UnmanagedMemoryAccessor.Read<T>(...) functions work perfectly.

更多推荐

将复杂结构写入内存映射文件

本文发布于:2023-08-01 04:28:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1265220.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:内存   结构   文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!