我尝试将以下结构写入内存映射文件,但数组仍然有问题(写入时抛出异常,结构不能包含引用)
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.
更多推荐
将复杂结构写入内存映射文件
发布评论