我正在用C++编写注入的.dll文件,我想使用命名管道与C#应用程序进行通信。如何使用命名管道在C++ .dll和C#应用程序之间发送消息?
现在,我在C#应用程序中使用内置的System.IO.Pipe .net类,并且使用C++中的常规函数。我没有太多的C++经验(阅读:这是我的第一个C++代码..),我在C#中经验丰富。
看来,与服务器和客户端的连接正在工作,唯一的问题是messaged没有被发送。我试图让.dll服务器,C#应用程序服务器,使管道方向InOut(双工),但似乎没有工作。
当我试图让.dll文件服务器,这将消息发送到C#应用程序,我使用的代码是这样的:
DWORD ServerCreate() // function to create the server and wait till it successfully creates it to return.
{
hPipe = CreateNamedPipe(pipename,//The unique pipe name. This string must have the following form: \\.\pipe\pipename
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_NOWAIT, //write and read and return right away
PIPE_UNLIMITED_INSTANCES,//The maximum number of instances that can be created for this pipe
4096 , // output time-out
4096 , // input time-out
0,//client time-out
NULL);
if(hPipe== INVALID_HANDLE_VALUE)
{
return 1;//failed
}
else
return 0;//success
}
void SendMsg(string msg)
{
DWORD cbWritten;
WriteFile(hPipe,msg.c_str(), msg.length()+1, &cbWritten,NULL);
}
void ProccesingPipeInstance()
{
while(ServerCreate() == 1)//if failed
{
Sleep(1000);
}
//if created success, wait to connect
ConnectNamedPipe(hPipe, NULL);
for(;;)
{
SendMsg("HI!");
if(ConnectNamedPipe(hPipe, NULL)==0)
if(GetLastError()==ERROR_NO_DATA)
{
DebugPrintA("previous closed,ERROR_NO_DATA");
DisconnectNamedPipe(hPipe);
ConnectNamedPipe(hPipe, NULL);
}
Sleep(1000);
}
和C#cliend这样的:
static void Main(string[] args)
{
Console.WriteLine("Hello!");
using (var pipe = new NamedPipeClientStream(".", "HyprPipe", PipeDirection.In))
{
Console.WriteLine("Created Client!");
Console.Write("Connecting to pipe server in the .dll ...");
pipe.Connect();
Console.WriteLine("DONE!");
using (var pr = new StreamReader(pipe))
{
string t;
while ((t = pr.ReadLine()) != null)
{
Console.WriteLine("Message: {0}",t);
}
}
}
}
我看到连接到.dll的C#客户端,但它不会收到任何消息。 我尝试以相反的方式执行此操作,正如前面所述,并试图使C#将消息发送给.dll。 DLL,它会在消息框中显示它们。 .dll被注入并连接到C#服务器,但是当它收到一条消息时,它刚刚崩溃了它注入的应用程序。
请帮助我,或者指导我如何使用C++和C#应用程序
哦,你应该把pipenames之间在C++和C#中大胆的差异。我浪费了时间解决这个问题,直到我找到了答案。 – 2017-10-10 16:46:37
@BrianFairservice - 完成:)。我很高兴这篇文章有帮助! – 2017-10-12 03:59:05