使用 MemoryMappedFile 从 CreateFileMappingW 共享 2 个数组到 C#

Sharing 2 arrays from CreateFileMappingW to C# using MemoryMappedFile

本文关键字:数组 共享 MemoryMappedFile CreateFileMappingW 使用      更新时间:2023-10-16

我创建了一个 c++ 项目来测试 CreateFileMappingW,以及一个创建 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
}

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

或者(你的偏移量是错误的......你实际上是在用完全相同的参数但不同的数组调用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);