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 );
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