Windows下python与c++之间的通信代码示例
时间: 2023-06-24 09:09:21 浏览: 129
python实现一个简单的udp通信的示例代码
在 Windows 下,Python 与 C++ 之间的通信可以通过多种方式实现,比如使用共享内存、管道、Socket 等。这里以使用 Socket 进行通信为例,给出一个简单的代码示例。
首先是 C++ 端的代码,使用 Winsock2 库实现 Socket 通信:
```cpp
#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int main() {
// 初始化 Winsock2 库
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cout << "WSAStartup failed!" << std::endl;
return -1;
}
// 创建 Socket
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET) {
std::cout << "socket failed!" << std::endl;
WSACleanup();
return -1;
}
// 绑定本地地址和端口
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(1234);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(s, (sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
std::cout << "bind failed!" << std::endl;
closesocket(s);
WSACleanup();
return -1;
}
// 监听连接请求
if (listen(s, SOMAXCONN) == SOCKET_ERROR) {
std::cout << "listen failed!" << std::endl;
closesocket(s);
WSACleanup();
return -1;
}
std::cout << "Waiting for connection..." << std::endl;
// 接受连接请求
SOCKET clientSock = accept(s, NULL, NULL);
if (clientSock == INVALID_SOCKET) {
std::cout << "accept failed!" << std::endl;
closesocket(s);
WSACleanup();
return -1;
}
std::cout << "Connected!" << std::endl;
// 接收数据并发送回复
char buffer[1024];
int recvLen;
while (true) {
recvLen = recv(clientSock, buffer, sizeof(buffer), 0);
if (recvLen <= 0) break;
buffer[recvLen] = '\0';
std::cout << "Received: " << buffer << std::endl;
send(clientSock, buffer, recvLen, 0);
}
// 关闭 Socket
closesocket(clientSock);
closesocket(s);
WSACleanup();
return 0;
}
```
接下来是 Python 端的代码,同样使用 Socket 库实现通信:
```python
import socket
# 创建 Socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
s.connect(('localhost', 1234))
print('Connected!')
# 发送数据并接收回复
while True:
message = input('Enter message: ')
s.send(message.encode())
if message == 'exit':
break
data = s.recv(1024)
print('Received:', data.decode())
# 关闭 Socket
s.close()
```
以上代码示例只是最简单的实现,实际应用中还需要考虑数据格式、数据长度、错误处理等问题。
阅读全文