所以我正在尝试使用命名管道在我将注入的C#服务器和C ++ .dll客户端之间进行通信。 我的命名管道在与C ++控制台应用程序一起使用时工作正常,但是当我在.dll中使用相同的方法时,服务器和客户端连接正常,但是当我尝试使用NamedPipeServerStream.Write()时,我的C#应用程序冻结。如果重要的话,它们都是x64。
关于为什么的任何想法?
C#服务器
Thread ServerThread;
private static NamedPipeServerStream _server;
private void Form1_Load(object sender, EventArgs e)
{
ServerThread = new Thread(ServerThreadSub);
ServerThread.Start();
}
void ServerThreadSub()
{
while (true)
{
_server = new NamedPipeServerStream("ConsolePipe", PipeDirection.Out, 1, PipeTransmissionMode.Message);
_server.WaitForConnection();
do
{
} while (_server.IsConnected);
_server.Close();
}
}
private void text_CurrentCommand_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Return)
{
if (text_CurrentCommand.Text != "")
{
if (_server.IsConnected)
{
try
{
byte[] buff = Encoding.UTF8.GetBytes(text_CurrentCommand.Text);
_server.Write(buff, 0, buff.Length); //Freezes here
}
catch
{
Log("Client Disconnected, Command Not Processed.");
}
}
else
{
Log("Command Not Processed. Client Not Connected.");
}
}
e.SuppressKeyPress = true;
}
}
C ++客户端
#define PIPE_NAME L"\\\\.\\pipe\\ConsolePipe"
#define BUFF_SIZE 1024
HANDLE hPipe;
DWORD WINAPI Main(LPVOID threadArgs)
{
while (true)
{
do
{
Sleep(1000);
hPipe = CreateFile(PIPE_NAME, GENERIC_READ, 0, nullptr, OPEN_EXISTING, 0, nullptr);
if (hPipe == NULL || hPipe == INVALID_HANDLE_VALUE) DeleteFile(PIPE_NAME);
} while (hPipe == NULL || hPipe == INVALID_HANDLE_VALUE);
DWORD mode = PIPE_READMODE_MESSAGE;
SetNamedPipeHandleState(hPipe, &mode, nullptr, nullptr);
bool success = false;
DWORD read;
while (true)
{
char chBuff[BUFF_SIZE];
success = ReadFile(hPipe, chBuff, (DWORD)strlen(chBuff), &read, nullptr);
if (success)
{
}
if (!success) break;
}
}
return 0;
}
另外我的另一个查询并不重要,有没有办法让NamedPipeServerStream.IsConnected刷新而不执行Read()或Write()?
先谢谢c:
答案 0 :(得分:0)
如果您要创建一个dll,我建议您使用 DllMain()
作为入口点,这可能是您的程序无法运行的主要原因之一
BOOL WINAPI DllMain(
HINSTANCE hinstDLL, // handle to DLL module
DWORD fdwReason, // reason for calling function
LPVOID lpReserved ) // reserved
{
// Perform actions based on the reason for calling.
switch( fdwReason )
{
case DLL_PROCESS_ATTACH:
// Initialize once for each new process.
// Return FALSE to fail DLL load.
break;
case DLL_THREAD_ATTACH:
// Do thread-specific initialization.
break;
case DLL_THREAD_DETACH:
// Do thread-specific cleanup.
break;
case DLL_PROCESS_DETACH:
// Perform any necessary cleanup.
break;
}
return TRUE; // Successful DLL_PROCESS_ATTACH.
}
更多信息https://msdn.microsoft.com/en-us/library/windows/desktop/ms682583(v=vs.85).aspx