Python ctypes: Python file object <-> C FILE *

前端 未结 6 775
深忆病人
深忆病人 2020-12-14 04:16

I am using ctypes to wrap a C-library (which I have control over) with Python. I want to wrap a C-function with declaration:

int fread_int( FILE * stream );
         


        
6条回答
  •  被撕碎了的回忆
    2020-12-14 05:02

    Well;

    I tried the fileno based solution, but was quite uncomfortable with opening the file twice; It was also not clear to me how to avoid the return value from fdopen() to leak.

    In the end I wrote a microscopic C-extension:

    static PyObject cfile(PyObject * self, PyObject * args) {
        PyObject * pyfile;
        if (PyArg_ParseTuple( 'O' , &pyfile)) {
           FILE * cfile = PyFile_AsFile( pyfile );
           return Py_BuildValue( "l" , cfile );
        else
            return Py_BuildValue( "" );
    }
    

    which uses PyFile_AsFile and subsequently returns the FILE * pointer as a pure pointer value to Python which passes this back to C function expecting FILE * input. It works at least.

    Joakim

提交回复
热议问题