使用 MemoryMappedFile 从 CreateFileMappingW 共享 2 个数组到 C#
Sharing 2 arrays from CreateFileMappingW to C# using MemoryMappedFile
我创建了一个 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);
相关文章:
- 如何在类中安全地访问 const 共享数组
- 在 MPI 中共享数组的一部分
- 在两个结构之间共享数组
- 使用IPC/共享内存将Integer数组从C++传递到Python
- 是否可以在并行区域中为共享 2D 数组创建选定元素的线程本地副本?(共享,私有,障碍:OPenMP)
- MPI_Get仅从共享内存区域读取数组的第一个元素
- 共享_ptr中多功能数组的类型是什么
- 唯一/共享 ptr 用于在数组超出范围后自动删除阵列
- 在 MPI (C++) 中共享整数数组
- CUDA 将大于线程计数的数组复制到共享内存
- C++11 在不同类之间共享固定大小的数组
- 当我可以创建共享指针时,为什么我不能创建指向数组的唯一指针?
- 对相邻数组元素使用共享内存
- 共享库的C 访问数组数据
- c++ WINAPI 共享内存结构数组
- C 98 Mutex中共享数组的锁定变量
- 提升共享指针数组
- 动态分配的 int 数组的共享指针触发了断点
- 如何在分叉之间共享数组
- 使用共享指针创建的链表数组