Created
July 15, 2025 04:35
-
-
Save Vizonex/d24b8d4c22027449b3ec175583a93aea to your computer and use it in GitHub Desktop.
python socketmodule exposure to cython
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from cpython.time cimport PyTime_t, PyTime_AsSecondsDouble | |
| from cpython.object cimport PyObject, PyTypeObject | |
| # After carefully observing socketmodule.h over from CPython and some | |
| # different versions of python I've determined it might be possible to | |
| # expose this data to the cython api by simply copying off socketmodule.h | |
| # NOTE: Some macros that could be utilized however were too dynamic to | |
| # be utilized here. However just getting the file descriptor object means a lot | |
| # and has potential of being utilized with libraries such as winloop/uvloop for | |
| # extra speed in the future. | |
| cdef extern from "socketmodule.h": | |
| ctypedef int SOCKET_T | |
| ctypedef struct PySocketSockObject: | |
| SOCKET_T sock_fd # Socket file descriptor | |
| int sock_family # Address family, e.g., AF_INET | |
| int sock_type # Socket type, e.g., SOCK_STREAM | |
| int sock_proto # Protocol type, usually 0 | |
| PyObject* (*errorhandler)() except NULL # Error handler; checks | |
| # errno, returns NULL and | |
| # sets a Python exception | |
| PyTime_t sock_timeout # Operation timeout in seconds | |
| # 0.0 means non-blocking | |
| ctypedef struct PySocketModule_APIObject: | |
| PyTypeObject *Sock_Type | |
| PyObject *error | |
| PyObject *timeout_error | |
| PySocketModule_APIObject* PySocketModule_ImportModuleAndAPI() | |
| ctypedef class _socket.socket [object PySocketSockObject, check_size ignore]: | |
| cdef: | |
| # Reason for making the majortiy of these constant is to prevent fiddling | |
| # with sockets from python's end. | |
| @property | |
| cdef const SOCKET_T fd(self): | |
| return self.sock_fd | |
| @property | |
| cdef const int family(self): | |
| return self.sock_family | |
| @property | |
| cdef const int type(self): | |
| return self.sock_type | |
| @property | |
| cdef double timeout(self): | |
| return PyTime_AsSecondsDouble(self.sock_type) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment