C++与Python之间的通信(IPC)
Communicate (IPC) between C++ to Python
我有应用程序服务器(server.py)和C++作为客户端(client.exe)。client.exe通过"命名管道"将变量发送到server.py。
问题是当我从server.py中的client.exe发送例如"Default message from client"时,只生成"D"(仅第一个字符发送)。
有人能帮我吗??
C++
服务器.py
from ctypes import *
PIPE_ACCESS_DUPLEX = 0x3
PIPE_TYPE_MESSAGE = 0x4
PIPE_READMODE_MESSAGE = 0x2
PIPE_WAIT = 0
PIPE_UNLIMITED_INSTANCES = 255
BUFSIZE = 4096
NMPWAIT_USE_DEFAULT_WAIT = 0
INVALID_HANDLE_VALUE = -1
ERROR_PIPE_CONNECTED = 535
MESSAGE = "Default answer from server "
szPipename = "\\.\pipe\mynamedpipe"
def ReadWrite_ClientPipe_Thread(hPipe):
chBuf = create_string_buffer(BUFSIZE)
cbRead = c_ulong(0)
while 1:
fSuccess = windll.kernel32.ReadFile(hPipe, chBuf, BUFSIZE,
byref(cbRead), None)
if ((fSuccess ==1) or (cbRead.value != 0)):
print chBuf.value
cbWritten = c_ulong(0)
fSuccess = windll.kernel32.WriteFile(hPipe,c_char_pc_char_p(MESSAGE),len(MESSAGE),byref(cbWritten),None)
else:
break
if ( (not fSuccess) or (len(MESSAGE) != cbWritten.value)):
print "Could not reply to the client's request from the pipe"
break
else:
print "Number of bytes written:", cbWritten.value
windll.kernel32.FlushFileBuffers(hPipe)
windll.kernel32.DisconnectNamedPipe(hPipe)
windll.kernel32.CloseHandle(hPipe)
return 0
def main():
THREADFUNC = CFUNCTYPE(c_int, c_int)
thread_func = THREADFUNC(ReadWrite_ClientPipe_Thread)
while 1:
hPipe = windll.kernel32.CreateNamedPipeA(szPipename,PIPE_ACCESS_DUPLEX,PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE, NMPWAIT_USE_DEFAULT_WAIT,None)
if (hPipe == INVALID_HANDLE_VALUE):
print "Error in creating Named Pipe"
return 0
fConnected = windll.kernel32.ConnectNamedPipe(hPipe, None)
if ((fConnected == 0) and (windll.kernel32.GetLastError() == ERROR_PIPE_CONNECTED)):
fConnected = 1
if (fConnected == 1):
dwThreadId = c_ulong(0)
hThread = windll.kernel32.CreateThread(None, 0, thread_func, hPipe, 0, byref(dwThreadId))
if (hThread == -1):
print "Create Thread failed"
return 0
else:
windll.kernel32.CloseHandle(hThread)
else:
print "Could not connect to the Named Pipe"
windll.kernel32.CloseHandle(hPipe)
return 0
if __name__ == "__main__":
main()
客户端.cpp
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#define BUFSIZE 512
int _tmain(int argc, TCHAR *argv[])
{
HANDLE hPipe;
LPTSTR lpvMessage=TEXT("Default message from client.");
TCHAR chBuf[BUFSIZE];
BOOL fSuccess = FALSE;
DWORD cbRead, cbToWrite, cbWritten, dwMode;
LPTSTR lpszPipename = TEXT("\\.\pipe\mynamedpipe");
if( argc > 1 )
lpvMessage = argv[1];
// Try to open a named pipe; wait for it, if necessary.
while (1)
{
hPipe = CreateFile(
lpszPipename, // pipe name
GENERIC_READ | // read and write access
GENERIC_WRITE,
0, // no sharing
NULL, // default security attributes
OPEN_EXISTING, // opens existing pipe
0, // default attributes
NULL); // no template file
// Break if the pipe handle is valid.
if (hPipe != INVALID_HANDLE_VALUE)
break;
// Exit if an error other than ERROR_PIPE_BUSY occurs.
if (GetLastError() != ERROR_PIPE_BUSY)
{
_tprintf( TEXT("Could not open pipe. GLE=%dn"), GetLastError() );
return -1;
}
// All pipe instances are busy, so wait for 20 seconds.
if ( ! WaitNamedPipe(lpszPipename, 20000))
{
printf("Could not open pipe: 20 second wait timed out.");
return -1;
}
}
// The pipe connected; change to message-read mode.
dwMode = PIPE_READMODE_MESSAGE;
fSuccess = SetNamedPipeHandleState(
hPipe, // pipe handle
&dwMode, // new pipe mode
NULL, // don't set maximum bytes
NULL); // don't set maximum time
if ( ! fSuccess)
{
_tprintf( TEXT("SetNamedPipeHandleState failed. GLE=%dn"), GetLastError() );
return -1;
}
// Send a message to the pipe server.
cbToWrite = (lstrlen(lpvMessage)+1)*sizeof(TCHAR);
_tprintf( TEXT("Sending %d byte message: "%s"n"), cbToWrite, lpvMessage);
fSuccess = WriteFile(
hPipe, // pipe handle
lpvMessage, // message
cbToWrite, // message length
&cbWritten, // bytes written
NULL); // not overlapped
if ( ! fSuccess)
{
_tprintf( TEXT("WriteFile to pipe failed. GLE=%dn"), GetLastError() );
return -1;
}
printf("nMessage sent to server, receiving reply as follows:n");
do
{
// Read from the pipe.
fSuccess = ReadFile(
hPipe, // pipe handle
chBuf, // buffer to receive reply
BUFSIZE*sizeof(TCHAR), // size of buffer
&cbRead, // number of bytes read
NULL); // not overlapped
if ( ! fSuccess && GetLastError() != ERROR_MORE_DATA )
break;
_tprintf( TEXT(""%s"n"), chBuf );
} while ( ! fSuccess); // repeat loop if ERROR_MORE_DATA
if ( ! fSuccess)
{
_tprintf( TEXT("ReadFile from pipe failed. GLE=%dn"), GetLastError() );
return -1;
}
CloseHandle(hPipe);
return 0;
}
如果您打印出服务器接收到的缓冲区的.raw,您可以看到它实际上得到了整个消息:
> print repr(chBuf.raw)
'Dx00ex00fx00ax00ux00lx00tx00 x00mx00ex00sx00sx00ax00gx00ex00 x00fx00rx00ox00mx00x00cx00lx00ix00ex00nx00tx00.x00x00x00x00x00 ... x00x00'
问题是,合法字符之间穿插着null值(\x00),当你试图打印chBuf.value时,这些值看起来像null终止符。那么,为什么所有的null都是?这是因为C++客户端正在发送wchar_t*消息(使用LPTSTR),但Python服务器需要一个char*字符串。
更改此行:
chBuf = create_string_buffer(BUFSIZE)
到此:
chBuf = create_unicode_buffer(BUFSIZE)
这应该可以解决问题。
哦,还有,看起来你在这里有一个复制粘贴错误:
fSuccess = windll.kernel32.WriteFile(hPipe,c_char_pc_char_p(MESSAGE),len(MESSAGE),byref(cbWritten),None)
应该是:
fSuccess = windll.kernel32.WriteFile(hPipe, c_char_p(MESSAGE),len(MESSAGE),byref(cbWritten),None)
我在Python代码中遇到了一个名称错误,直到我更改了它。
也许服务器应该尝试从管道中循环读取,直到您期望访问的所有数据都已到达(根据您与客户端的协议,例如,直到读取空终止符)。
相关文章:
- IPC使用多个管道和分支进程来运行Python程序
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 是否可以使用winusb同时与多个相同的usb设备进行通信
- 混淆了如何使用IDL与Ethovision进行通信
- C++ Boost::asio串行通信与Arduino无法写入
- 我是否需要包含隐式使用/与 WindowsAPI 通信"Windows.h"?
- 通过TCP的PvP通信问题
- C++一个线程如何正确通信其任务已完成?
- 如何将 Firebase 与基于 Linux 的客户端应用配合使用,以便与服务器进行双向消息通信
- 我们可以通过 IPC 传递具有动态管理成员的类对象吗?
- 删除功能不适用于串行通信后多个循环中的多个实例
- 网站和C++程序在同一台 Linux PC 上的通信
- 通过插槽和信号在不同线程中的两个qt对象之间进行通信
- 使用 pybind11 共享 MPI 通信器
- 进程间通信堆内存
- 重复Handle()是否执行任何解释性通信(IPC),如果不是为什么目标参数
- 远程、IPC 和线程场景中微服务的低延迟通信
- 了解RProperty IPC通信
- C++与Python之间的通信(IPC)
- IPC: c++程序与一组bash脚本和c++程序的通信