简体   繁体   English

使用python3和c / c ++嵌入套接字

[英]socket embedding with python3 and c/c++

I have a process run on python3,it have to create a module to call c library,but in c lib it have to call socket connected from python3,and result for python3 我有一个在python3上运行的进程,它必须创建一个模块来调用c库,但是在c lib中它必须调用从python3连接的socket,并且结果为python3

[python3]--->[c]--->[c socket]--->[python socket]----->[c function]----->[python3] [python3] ---> [c] ---> [c socket] ---> [python socket] -----> [c function] -----> [python3]

how to convert python type socket to c type socket ? 如何将python类型套接字转换为c类型套接字?

help me an example,thanks ! 帮帮我一个例子,谢谢!

AC socket is just a file descriptor, referred to by number. AC套接字只是一个文件描述符,用数字表示。

A Python socket is an object that wraps up a file descriptor. Python套接字是一个包装文件描述符的对象。 You can get the file descriptor number out of it with the fileno method. 您可以使用fileno方法从中获取文件描述符编号。

For example: 例如:

def call_c_code_with_socket(my_socket):
    c_library.c_func(my_socket.fileno())

(I'm assuming you're on POSIX here; on Windows, things are a bit more complicated, because you usually use WSASocket and friends, which deal in opaque SOCKET handles instead of simple integers.) (我假设你在这里使用POSIX;在Windows上,事情有点复杂,因为你通常使用WSASocket和朋友,它处理不透明的SOCKET句柄而不是简单的整数。)

Going the other way is a bit trickier. 走另一条路有点棘手。

If you've created a socket in C, and want to use it in Python, you need the family, type, and proto values as well as the fd number—but if you have them, fromfd is the answer. 如果您在C中创建了一个套接字,并希望在Python中使用它,那么您需要family,type和proto值以及fd数字 - 但是如果你有它们, fromfd就是答案。

However, if you create a socket in Python, send its file descriptor to C, and get it back, you don't want to create a new socket object; 但是,如果在Python中创建套接字,将其文件描述符发送到C,并将其取回,则不希望创建新的套接字对象; you want to find the old one. 你想找到旧的。 You might consider creating a dict mapping fd numbers to socket objects for that case. 您可以考虑为该情况创建一个将fd数字映射到socket对象的dict

Finally, be careful not to confuse one piece of your code by doing odd things with another. 最后,注意不要将一段代码与另一段代码混淆。 If you've read half of the next protocol message into a buffer in C, Python is going to want that half-message. 如果您已将下一个协议消息的一半读入C中的缓冲区,那么Python将需要该半消息。 If you've set the socket to nonblocking mode in Python, it's still going to be non-blocking in C. And so on. 如果您在Python中将套接字设置为非阻塞模式,那么它在C中仍将是非阻塞的。依此类推。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM