gpt4 book ai didi

c# - 命名管道 C# 服务器 C++ .dll 客户端不工作?

转载 作者:太空宇宙 更新时间:2023-11-04 13:09:39 25 4
gpt4 key购买 nike

所以我尝试使用命名管道在 C# 服务器和我将注入(inject)的 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;
}

我还有另一个不太重要的查询,是否有任何方法可以在不执行 Read() 或 Write() 的情况下让 NamedPipeServerStream.IsConnected 刷新?

提前致谢:

最佳答案

如果您正在创建一个 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

关于c# - 命名管道 C# 服务器 C++ .dll 客户端不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40504905/

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