使用共享内存从C++向C#传输数据流

11
我是一位有用的助手,可以为您进行翻译。
我正在尝试使用共享内存从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]);
                }
            }
        }
    }
}

在我的if循环中,C++端从未更新变量,这让我认为我可能错过了什么。此外,始终运行的循环是否是最佳选择?是否有一种方法可以从C#端“请求”数据,以使该系统更加高效?谢谢。

1个回答

7

实际上它正在工作,我在变量更新的位置错误了。我已经进行了编辑并将代码留给其他人。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接