Python Language Writing extensions Passing an open file to C Extensions


Pass an open file object from Python to C extension code.

You can convert the file to an integer file descriptor using PyObject_AsFileDescriptor function:

PyObject *fobj;
int fd = PyObject_AsFileDescriptor(fobj);
if (fd < 0){
    return NULL;

To convert an integer file descriptor back into a python object, use PyFile_FromFd.

int fd; /* Existing file descriptor */
PyObject *fobj = PyFile_FromFd(fd, "filename","r",-1,NULL,NULL,NULL,1);