Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am attempting to stream data from a c++ application to a C# application using shared memory. Based on example I found, I have:

c++ (sending)

    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# (receiving)

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]);
                }
            }
        }
    }
}

The c++ side never updates the variable, making me think i have missed something in my if-loop. Additionally, is a always-running loop the best way to go here? Is there a way to 'request' the data somehow from the C# side, to make this a more efficient system? Thank you.

like image 256
anti Avatar asked Jun 01 '16 15:06

anti


1 Answers

..Actually this is working, I had the update for the variable in the wrong place. I have edited and will leave the code for others.

like image 59
anti Avatar answered Oct 07 '22 00:10

anti