通过共享内存将数据从 C++ 流式传输到 C#

stream data from c++ to c# over shared memory

本文关键字:传输 C++ 共享 内存 数据      更新时间:2023-10-16

我正在尝试使用共享内存将数据从 c++ 应用程序流式传输到 C# 应用程序。根据我发现的示例,我有:

C++(发送)

    struct Pair {
    int length; 
    float data[3];
};
#include <windows.h>
#include <stdio.h>
struct Pair* p;
HANDLE handle;
float dataSend[3]{ 22,33,44 };
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;
    }
}

int main()
{
    if (startShare() == true)
    {
            while (true)
            {
                if (p != 0) {
                //dataSend[0] += 1;  // here the value doesn't refresh
                for (int h = 0; h < 3; h++)
                {
                    p->data[h] = dataSend[h];
                }
             //dataSend[0] += 1;  // here it does
            }

        else
            puts("create shared memory error");
    }
    }
    if (handle != NULL)
        CloseHandle(handle);
    return 0;
}

C# (接收)

namespace sharedMemoryGET
{
    class Program
    {
        public static float[] data = new float[3];
        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;
            }
        }
       public static void Main(string[] args)
        {
            while (true)
            {
                if (MemOpen())
            {
                    byte[] blen = new byte[4];
                    mmfvs.Read(blen, 0, 4);
                    int len = blen[0] + blen[1] * 256 + blen[2] * 65536 + blen[2] * 16777216;
                    byte[] bPosition = new byte[12];
                    mmfvs.Read(bPosition, 0, 12);
                    Buffer.BlockCopy(bPosition, 0, data, 0, bPosition.Length);
                    Console.WriteLine(data[0]);
                }
            }
        }
    }
}

c++ 端从不更新变量,让我觉得我在 if 循环中错过了一些东西。此外,始终运行的循环是最好的方法吗?有没有办法以某种方式从 C# 端"请求"数据,使其成为更高效的系统?谢谢。

..实际上这是有效的,我在错误的地方更新了变量。我已经编辑并将代码留给其他人。