tags:

views:

69

answers:

2

Hello,

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

Now; I would like to open file in python, and then use the Python file-object (in some way??) to get access to the underlying FILE * object and pass that to the C-function:

# Python
fileH = open( file , "r")
value = ctypes_function_fread_int( ????? )
fileH.close()

Is the Python file <-> FILE * mapping at all possible?

Joakim

+5  A: 

A Python file object does not necessarily have an underlying C-level FILE * -- at least, not unless you're willing to tie your code to extremely specific Python versions and platforms.

What I would recommend instead is using the Python file object's fileno to get a file descriptor, then use ctypes to call the C runtime library's fdopen to make a FILE * out of that. This is a very portable approach (and you can go the other way, too). The big issue is that buffering will be separate for the two objects opened on the same file descriptor (the Python file object, and the C FILE *), so be sure to flush said objects as often as needed (or, open both as unbuffered, if that's more convenient and compatible with your intended use).

Alex Martelli
Thanks a lot -I had this feeling that the C-level FILE * would not be very robust. I did not know about the fileno attribute of the python file object - but that seems like a natural way to go.
A: 

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