From: Nathaniel S. <nj...@po...> - 2012-12-04 00:16:39
|
On Mon, Dec 3, 2012 at 11:50 PM, Chris Barker - NOAA Federal <chr...@no...> wrote: > On Mon, Dec 3, 2012 at 2:21 PM, Nathaniel Smith <nj...@po...> wrote: >> For the file handle, I would just write >> >> cdef FILE *fp = fdopen(file_obj.fileno(), "w") >> >> and be done with it. This will work with any version of Python etc. > > yeah, that makes sense -- though what if you want to be able to > read_to/write_from a file that is already open, and in the middle of > the file somewhere -- would that work? > > I just posted a question to the Cython list, and indeed, it looks like > there is no easy answer to the file issue. Yeah, this is a general problem with the Python file API, trying to hook it up to stdio is not at all an easy thing. A better version of this code would skip that altogether like: cdef void write_to_pyfile(png_structp s, png_bytep data, png_size_t count): fobj = <object>png_get_io_ptr(s) pydata = PyString_FromStringAndSize(data, count) fobj.write(pydata) cdef void flush_pyfile(png_structp s): # Not sure if this is even needed fobj = <object>png_get_io_ptr(s) fobj.flush() # in write_png: write_png_c(<png_byte*>pix_buffer, width, height, NULL, <void*>file_obj, write_to_pyfile, flush_pyfile, dpi) But this is a separate issue :-) (and needs further fiddling to make exception handling work). Or if you're only going to work on real OS-level file objects anyway, you might as well just accept a filename as a string and fopen() it locally. Having Python do the fopen just makes your life harder for no reason. -n |