使用MemoryMappedFile

时间:2019-07-04 03:25:26

标签: c# c++

我创建了一个用于测试CreateFileMappingW的c ++项目,以及一个在其中创建2个数组的结构。我能够通过MemoryMappedFile读取C#项目中的第一个数组,但是由于某种原因,我无法获取第二个数组的值。

C ++代码

#include <windows.h>
#include <stdio.h>
#include <iostream>
struct StructOfArray {

    int array1[3];
    int array2[2];

};
struct StructOfArray* datatoget;
HANDLE handle;
int main() {

    handle = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(StructOfArray), L"DataSend");
    datatoget = (struct StructOfArray*) MapViewOfFile(handle, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(StructOfArray));

    datatoget->array1[0] = 10;
    datatoget->array1[1] = 15;
    datatoget->array1[2] = 20;

    datatoget->array2[0] = 200;
    datatoget->array2[1] = 203;

}

C#项目:

    int[] firstArray = new int[3];
    int[] secondArray = new int[2];

    string filePath = "DataSend";
    mmf = MemoryMappedFile.OpenExisting(filePath);
    mmfvs = mmf.CreateViewStream();

    byte[] bPosition = new byte[1680];
    mmfvs.Read(bPosition, 0, 1680);
    Buffer.BlockCopy(bPosition, 0, firstArray, 0, bPosition.Length);//worked fine
    Buffer.BlockCopy(bPosition, 0, secondtArray, 0, bPosition.Length);//did not work

    for (int i = 0; i < 3; i++)
    {
        console.WritLine(firstArray[i])//worked fine
    }
    for (int i = 0; i < 2; i++)
    {
        console.WritLine(secondtArray[i])// not sure how to take second array
    }

1 个答案:

答案 0 :(得分:1)

使用MemoryMappedViewAccessor

mmf = MemoryMappedFile.OpenExisting(filePath);

using (var accessor = mmf.CreateViewAccessor(0, Marshal.SizeOf(typeof(int)) * 5))
{
    int intSize = Marshal.SizeOf(typeof(int));

    //Read first array..
    for (long i = 0; i < 3 * intSize; i += intSize)
    {
        int value = 0;
        accessor.Read(i, out value);
        firstArray[i] = value;
    }

    //Read second array..
    for (long i = 0; i < 2 * intSize; i += intSize)
    {
        int value = 0;
        accessor.Read(i, out value);
        secondArrayArray[i] = value;
    }
}

OR(您的偏移量是错误的。您实际上是在使用完全相同的参数但使用不同的数组调用BlockCopy-IE:相同的偏移量:0):

var intSize = Marshal.SizeOf(typeof(int));

//Copy first array..
Buffer.BlockCopy(bPosition, 0, firstArray, 0, intSize * firstArray.Length);

//Copy second array..
Buffer.BlockCopy(bPosition, intSize * firstArray.Length, secondArray, 0, intSize * secondArray.Length);