包装C+的问题+;类转换为python
对于我的项目(ia的游戏),我需要一个C网络接口。我想在Python中编写我的项目,所以我用C TCP套接字函数创建了一个C++包装器,用它在Python代码中使用<代码> C类型<代码>:包装C+的问题+;类转换为python,python,c++,c,sockets,ctypes,Python,C++,C,Sockets,Ctypes,对于我的项目(ia的游戏),我需要一个C网络接口。我想在Python中编写我的项目,所以我用C TCP套接字函数创建了一个C++包装器,用它在Python代码中使用 C类型: #include <iostream> #include <string> #include "Socket.h" #include "stdio.h" void Socket::s_connect(char *host, int port){ const char *str
#include <iostream>
#include <string>
#include "Socket.h"
#include "stdio.h"
void Socket::s_connect(char *host, int port){
const char *str;
pe = getprotobyname("tcp");
if (!pe){
perror("Error get protocol");
exit(1);
}
f = socket(AF_INET, SOCK_STREAM, pe->p_proto);
if (f == -1){
perror("Error create socker");
exit(1);
}
s_in.sin_family = AF_INET;
s_in.sin_port = htons(port);
s_in.sin_addr.s_addr = inet_addr(host);
if (connect(f, (const struct sockaddr *&)s_in, sizeof(s_in)) == -1){
perror("Error on connect");
close(f);
}
}
void Socket::s_send(char *msg){
if (write(f, msg, strlen(msg)) == -1){
printf("error write\n");
perror("write");
exit(1);
}
}
char *Socket::s_recv(){
char *buff;
int ret;
buff = (char *)malloc(4096);
ret = read(f, buff, 4096);
if (ret < 0){
if (close(f))
exit(1);
}
return buff;
}
extern "C" {
Socket *Socket_new()
{
return (new Socket);
}
void Socket_connect(Socket *sock, char *host, int port)
{
sock->s_connect(host, port);
}
void Socket_send(Socket *sock, char *msg)
{
sock->s_send(msg);
}
}
和我的Ext:Cuth.c Func < /Cord>无法读取Python发送的字符串,我可以发送端口号,但是我的C++函数不能读取主机的字符串值。 如果我将
char*
更改为std::string
我会遇到同样的问题。
我做错什么了吗
感谢您使用Python3版本,
ctypes
模块的文档说明PythonUnicode字符串(str
)对应于C中的宽字符数组(wchar\u t*
),Python字节字符串(bytes
)对应于窄字符数组(char*
)
因此,根据您是否希望实际处理unicode字符,您应该:
- 使用
Python端(普通):bytes
- 或者使用
C端(可能更难…)wchar\u t
socket
模块要容易得多。是的,我知道,但我的projet需要一个C网络接口,这是我的项目说明之一。嗯,你使用Python2还是Python3?当你说“不能读取主机的字符串值”时,到底发生了什么?挂在什么位置,你把Python映射到C++的什么地方?code>libsocket.so是标准C网络库的一部分。您是否调用C++的DLL与C库的名称相同?
#ifndef SOCKET_HPP_
# define SOCKET_HPP_
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
class Socket {
int f, port;
struct protoent *pe;
struct sockaddr_in s_in;
char *ip;
public:
void s_connect(char *host, int port);
void s_send(char * msg);
char *s_recv();
};
#endif
#!/usr/bin/python
import sys
from ctypes import cdll
lib = cdll.LoadLibrary('./libsocket.so')
class Socket(object):
def __init__(self):
self.obj = lib.Socket_new()
def s_connect(self, host, port):
print(host, port)
lib.Socket_connect(self.obj, host, int(port))
def s_send(self, msg):
lib.Socket_send(self.obj, msg)
def s_recv(self):
lib.Socket_recv(self.obj)
def main(arg):
sock = Socket()
sock.s_connect(arg[1], arg[2])
sock.s_send("coucou")
if __name__ == "__main__":
main(sys.argv)
sock.s_connect(arg[1].encode('latin1'), arg[2])