使用命名管道在C#和C ++应用程序之间进行持续通信

时间:2018-07-07 09:40:53

标签: c# c++ winapi pipe message

我是IPC的新朋友。我尝试创建一个客户端服务器应用程序,其中我的服务器是C ++应用程序,而客户端是C#。在此应用程序中,客户端将消息发送到服务器,并根据该消息服务器发送操作。 服务器基本上将图像帧发送给客户端。

使用以下代码,我可以将单个帧发送给客户端

我的C ++代码

int _count = 0;
const int _scale = 255;
int _bufferSize = ROW * COL;
UINT8 _imageBuffer[391680];
Mat _image;
std::cout << "Server Starting\n";
HANDLE hPipe1 = CreateNamedPipe(_T("\\\\.\\pipe\\HyperPipe1"),
    PIPE_ACCESS_DUPLEX,
    PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
    PIPE_UNLIMITED_INSTANCES,
    4096,
    4096,
    0,
    NULL);
std::cout << "Server Created Succesfully\n";
ConnectNamedPipe(hPipe1, NULL);
std::cout << "Sending Frame to Client";
_image = imread("C:\\Users\\Chandrapal Singh\\Desktop\\New folder\\Image.bmp", IMREAD_GRAYSCALE);
//_image.clone().convertTo(_image, CV_16U, _scale);
for (int _imageRow = 0; _imageRow < _image.rows; _imageRow++)
{
    for (int _imageCol = 0; _imageCol < _image.cols; _imageCol++)
    {
        _imageBuffer[_count] = _image.at<UINT8>(_imageRow, _imageCol);
        _count++;
    }
}
DWORD bytesWritten = 0;
WriteFile(hPipe1, _imageBuffer, sizeof(_imageBuffer) * sizeof(UINT8), &bytesWritten, NULL);

我的C#代码

int _imageRowSize = 544;
int _imageColSize = 720;
int _count = 0;
byte[] buffer = new byte[_imageColSize * _imageRowSize];
Image<Gray, Byte> image = new Image<Gray, Byte>(_imageColSize,_imageRowSize);
Console.WriteLine("Creating Client Pipe");
NamedPipeClientStream pipe = new NamedPipeClientStream(".", "HyperPipe1", PipeDirection.InOut);
Console.WriteLine("Pipe Created Successfully, Connecting to Server");
pipe.Connect();
Console.WriteLine("Successfully, Connected to Server");
using (MemoryStream ms = new MemoryStream())
{
    while (true)
    {
        _count = 0;      
        int read = pipe.Read(buffer, 0, buffer.Length);
        for (int _imageRow = 0; _imageRow < 544; _imageRow++)
        {
            for (int _imageCol = 0; _imageCol < 720; _imageCol++)
            {
                try
                {
                    image.Data[_imageRow, _imageCol, 0] = buffer[_count];
                }catch(Exception exception)
                {
                    Console.WriteLine(exception);
                }
                _count++;
            }
        }
        CvInvoke.Imshow("Image", image);
        Console.WriteLine(_count);
        if (read <= 0)
            break;
    }
}

我想知道如何将消息从C#发送到C ++,以及我的C ++如何连续将图像帧发送到C#。

1 个答案:

答案 0 :(得分:-3)

在服务器和客户端中创建管道的两个实例或另一个管道,并使用线程同时读写,而不会阻塞其他正在运行的操作

相关问题