Python | Passing Filenames to Extension in C
Filename has to be encoded according to the system’s expected filename encoding before passing filenames to C library functions.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
If there is already a existing
PyObject * that needs to be converted as a filename, then use the code given below :
If a filename is to be returned back to Python, use the following code given below –
Code #3 :
Dealing with filenames in a portable way is a tricky problem that is best left to Python. Filenames will be handled in a manner that, if one uses the above in extension C code.
Passing Open Files to C Extensions –
Code #4 : To convert a file to an integer file descriptor, use
The resulting file descriptor is obtained by calling the
fileno() method on fobj. Thus, any object that exposes a descriptor in this manner should work (e.g., file, socket, etc.). A descriptor can be passed to various low-level C functions that expect to work with files.
PyFile_FromFd() is used to convert an integer file descriptor back into a Python object.
Code #5 :
The arguments to
PyFile_FromFd() mirror those of the built-in open() function. NULL values simply indicate that the default settings for the encoding, errors, and newline arguments are being used.