gpt4 book ai didi

c# - C++ NamedPipeClientStream 发送数据

转载 作者:行者123 更新时间:2023-11-28 07:37:38 29 4
gpt4 key购买 nike

我想通过管道将数据从 C++ DLL 文件发送到 C# pip 服务器。服务器已编程,使用 C# 客户端可以很好地获取数据。

我的简单 C# 客户端代码:

        System.IO.Pipes.NamedPipeClientStream pipeClient = new System.IO.Pipes.NamedPipeClientStream(".", "testpipe", System.IO.Pipes.PipeDirection.InOut, System.IO.Pipes.PipeOptions.None);

if (pipeClient.IsConnected != true) { pipeClient.Connect(); }

StreamReader sr = new StreamReader(pipeClient);
StreamWriter sw = new StreamWriter(pipeClient);

try
{
sw.WriteLine("Test Message");
sw.Flush();
pipeClient.Close();
}
catch (Exception ex) { throw ex; }
}

但是,我不太喜欢用 C++ 实现这个客户端。我需要哪些头文件?你能给我一个简单的例子吗?谢谢!

编辑:感谢您的回复!为了测试它,我创建了一个 C++ 程序并编译了以下内容:

        #include "stdafx.h"


int _tmain(int argc, _TCHAR* argv[])
{
HANDLE pipe = CreateFile(
L"testpipe",
GENERIC_READ, // only need read access
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL
);

if (pipe == INVALID_HANDLE_VALUE) {
// look up error code here using GetLastError()
DWORD err = GetLastError();
system("pause");
return 1;
}


// The read operation will block until there is data to read
wchar_t buffer[128];
DWORD numBytesRead = 0;
BOOL result = ReadFile(
pipe,
buffer, // the data from the pipe will be put here
127 * sizeof(wchar_t), // number of bytes allocated
&numBytesRead, // this will store number of bytes actually read
NULL // not using overlapped IO
);

if (result) {
buffer[numBytesRead / sizeof(wchar_t)] = '?'; // null terminate the string
// wcout << "Number of bytes read: " << numBytesRead << endl;
// wcout << "Message: " << buffer << endl;
} else {
// wcout << "Failed to read data from the pipe." << endl;
}

// Close our pipe handle
CloseHandle(pipe);


system("pause");
return 0;

return 0;
}

但是,当我运行它时,(pipe == INVALID_HANDLE_VALUE) 为真。调试显示 DWORD err = GetLastError();具有值 2,尽管服务器正在运行。有人有想法吗?

最佳答案

你可以在网上找到很多例子。搜索命名管道示例 c++。例如:http://www.avid-insight.co.uk/2012/03/introduction-to-win32-named-pipes-cpp/

关于c# - C++ NamedPipeClientStream 发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16429905/

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