Cesar Augusto
Cesar Augusto

Reputation: 151

Sharing 2 arrays from CreateFileMappingW to C# using MemoryMappedFile

I created a c++ project to test CreateFileMappingW, along with a struct where i create 2 arrays. I was able to read the first array in my C# project via MemoryMappedFile, but for some reason I couldn't get the values for the second array.

C++ code

#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# project:

    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
    }

Upvotes: 1

Views: 103

Answers (1)

Brandon
Brandon

Reputation: 23498

Use a 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 (your offsets are wrong.. you are literally calling BlockCopy with the exact same parameters but different arrays -- IE: same offsets: 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);

Upvotes: 1

Related Questions