Writing complex structure to memory-mapped-file

有些话、适合烂在心里 提交于 2020-01-06 20:00:05

问题


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;
}

I use this calling for writing:

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

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


回答1:


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];
}

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];
}

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



来源:https://stackoverflow.com/questions/33649565/writing-complex-structure-to-memory-mapped-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!