gpt4 book ai didi

c# - c++和c#之间通过管道进行通信

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:36:16 35 4
gpt4 key购买 nike

我想通过管道将数据从 C# 应用程序发送到 C++ 应用程序。这是我所做的:

这是 C++ 客户端:

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>


int _tmain(int argc, _TCHAR* argv[]) {

HANDLE hFile;
BOOL flg;
DWORD dwWrite;
char szPipeUpdate[200];
hFile = CreateFile(L"\\\\.\\pipe\\BvrPipe", GENERIC_WRITE,
0, NULL, OPEN_EXISTING,
0, NULL);

strcpy(szPipeUpdate,"Data from Named Pipe client for createnamedpipe");
if(hFile == INVALID_HANDLE_VALUE)
{
DWORD dw = GetLastError();
printf("CreateFile failed for Named Pipe client\n:" );
}
else
{
flg = WriteFile(hFile, szPipeUpdate, strlen(szPipeUpdate), &dwWrite, NULL);
if (FALSE == flg)
{
printf("WriteFile failed for Named Pipe client\n");
}
else
{
printf("WriteFile succeeded for Named Pipe client\n");
}
CloseHandle(hFile);
}
return 0;

这里是c#服务器

using System;
using System.IO;
using System.IO.Pipes;
using System.Threading;
namespace PipeApplication1{

class ProgramPipeTest
{

public void ThreadStartServer()
{
// Create a name pipe
using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("\\\\.\\pipe\\BvrPipe"))
{
Console.WriteLine("[Server] Pipe created {0}", pipeStream.GetHashCode());

// Wait for a connection
pipeStream.WaitForConnection();
Console.WriteLine("[Server] Pipe connection established");

using (StreamReader sr = new StreamReader(pipeStream))
{
string temp;
// We read a line from the pipe and print it together with the current time
while ((temp = sr.ReadLine()) != null)
{
Console.WriteLine("{0}: {1}", DateTime.Now, temp);
}
}
}

Console.WriteLine("Connection lost");
}

static void Main(string[] args)
{
ProgramPipeTest Server = new ProgramPipeTest();

Thread ServerThread = new Thread(Server.ThreadStartServer);

ServerThread.Start();

}
}

当我启动服务器然后从客户端返回 2 的客户端 GetLastErrror(系统找不到指定的文件。)

对此有任何想法。谢谢

最佳答案

我猜测,在服务器中创建管道时不需要“\.\Pipe\”前缀。 examples调用我见过的 NamedPipeServerStream 构造函数只是传入管道名称。例如

using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("BvrPipe"))

您可以使用 SysInternals 进程资源管理器列出打开的管道及其名称。这应该可以帮助您验证管道的名称是否正确。参见 this询问详情。

关于c# - c++和c#之间通过管道进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1906561/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com