[Pyrex] Mapping a stdio-FILE to a Python-file

Joachim Saul saul at gfz-potsdam.de
Tue Nov 18 10:02:30 CET 2003


* Greg Ewing [2003-11-18 01:09]:
> Joachim Saul <saul at gfz-potsdam.de>:
>
> > What is the best way to map a stdio-FILE to a Python-file object in
> > Pyrex?
>
> You could use the following Python/C API function:
>
>   FILE* PyFile_AsFile(PyFileObject *p)
>     Returns the file object associated with p as a FILE*.

This is an obvious approach, which I overlooked. Thanks for
pointing it out. There is, however, a problem when I translate the
avove (Pyrex 0.9):

    /home/saul/Python/SeisPy/MseedPy/_mseed.pyx:85:38: Expected ')'

Which means that it apparently doesn't expect the argument to be a
pointer. Writing instead

    FILE* PyFile_AsFile(PyFileObject)

works. Perhaps this is just what you were referring to? Also, I
would have expected

    cdef FILE *p
    p = PyFile_AsFile("dummy")

to produce some sort of an error, which it doesn't and which in
weakly typed language as Python may be problematic. In my actual
class method the file is typified (see below), so that for me this
doesn't really represent a problem in practice. However, the
typification of a 'file' itself poses a "problem", which again
may have a solution which I overlooked. As stated in my previous
email, what I do right now is (after some modification)

cdef extern from "fileobject.h":
    ctypedef class __builtin__.file [object PyFileObject]:
        pass

and it works as expected. Yet it seems to be a rather crude hack.
Any better ("more cool-looking") way to achieve something like

    def fromfile(self, file f):
    ...

?

> > Ideally, I would like Pyrex to directly map the file object to a FILE,
> > since both are standard types in their respective languages.
>
> That's an idea worth considering -- I'll add it to my list.

Great!

Cheers,
Joachim




More information about the Pyrex mailing list