Buffer.BlockCopy数组2d C ++到C#共享内存

时间:2019-01-16 16:29:44

标签: c# c++

我编写了一个c ++程序,该程序通过memorystream发送一个多数组到c#应用程序。但是我不知道可以使用BlockCopy来数组多:

这是我的程序c ++,可以发送多个数组

struct Pair {

    std::pair<int, int> players;
};

struct Pair* p;
HANDLE handle;

float dataSend[70];

bool startShare()
{
    try
    {
        handle = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(Pair), L"DataSend");
        p = (struct Pair*) MapViewOfFile(handle, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, sizeof(Pair));
        return true;
    }
    catch (...)
    {
        return false;
    }

}
for (int i = 0; i < 70; i++)
{

    int r1 = rand() % 10 + 1;
    int r2 = rand() % 10 + 1;
    p->players = { r1,r2 };

}

示例输出:

 players  0 - [10][2]
 players  1 - [100][22]
 players 2 - [1][26]
 players 3 - [50][211]
 players 4 - [32][23]

我的C#程序读取:

public static int[,] data = new int[70, 1];
public static MemoryMappedFile mmf;
public static MemoryMappedViewStream mmfvs;

static public bool MemOpen()
{
    try
    {
        mmf = MemoryMappedFile.OpenExisting("DataSend");
        mmfvs = mmf.CreateViewStream();
        return true;
    }
    catch
    {
        return false;
    }

}

// here need be somethings like   byte[,] bPosition = new byte[70,1];
byte[] bPosition = new byte[70];
mmfvs.Read(bPosition, 0, 100);
Buffer.BlockCopy(bPosition, 0, data, 0, bPosition.Length);
 for (int i = 0; i< data.Length; i++)
 {
    for(int j=0;j<1;j++)
    {

      Console.WriteLine(data[i][j]);

    }

}

示例接收:

 data  0 - [10][2]
 data  1 - [100][22]
 data 2 - [1][26]
 data 3 - [50][211]
 data 4 - [32][23]

我编写了一个c ++程序,该程序通过memorystream发送一个多数组到c#应用程序。但是我不知道可以使用BlockCopy来数组多:

这是我的程序c ++,可以发送多个数组

1 个答案:

答案 0 :(得分:0)

尝试以下操作:

              MemoryStream stream = new MemoryStream();
              byte[] buffer = new byte[70 * 2 * sizeof(int)];
              stream.Read(buffer, 0, 70 * 2 * sizeof(int));
              for (int i = 0; i< 70; i++)
              {
                  for (int j = 0; j < 2; j++)
                  {
                      Console.WriteLine(BitConverter.ToUInt32(buffer,(i * 2 * sizeof(int)) + (j * sizeof(int))));
                  }
              }

           IntPtr bufferPtr = Marshal.AllocHGlobal(BUFFER_SIZE);

            //you need to allocate memory before calling the routing

            byte[] buffer = new byte[BUFFER_SIZE];
            Marshal.Copy(bufferPtr, buffer, 0, BUFFER_SIZE);
            for (int i = 0; i < 70; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    Console.WriteLine(BitConverter.ToUInt32(buffer, (i * 2 * sizeof(int)) + (j * sizeof(int))));
                }
            }

            //method 2
            int[,] array = new int[40, 2];
            IntPtr bufferPtr2 = Marshal.AllocHGlobal(Marshal.SizeOf(array));

            //call routine then you code below to fill managed memory.
            Marshal.PtrToStructure(bufferPtr2, array);