39
39
40
40
#include " numpy/arrayobject.h"
41
41
#include " agg_py_transforms.h"
42
+ #include " file_compat.h"
42
43
43
44
#ifndef M_PI
44
45
#define M_PI 3.14159265358979323846
@@ -2028,44 +2029,42 @@ RendererAgg::write_rgba(const Py::Tuple& args)
2028
2029
2029
2030
FILE *fp = NULL ;
2030
2031
Py::Object py_fileobj = Py::Object (args[0 ]);
2031
-
2032
- #if PY3K
2033
- int fd = PyObject_AsFileDescriptor (py_fileobj.ptr ());
2034
- PyErr_Clear ();
2035
- #endif
2032
+ PyObject* py_file = NULL ;
2033
+ bool close_file = false ;
2036
2034
2037
2035
if (py_fileobj.isString ())
2038
2036
{
2039
- std::string fileName = Py::String (py_fileobj);
2040
- const char *file_name = fileName.c_str ();
2041
- if ((fp = fopen (file_name, " wb" )) == NULL )
2042
- throw Py::RuntimeError (
2043
- Printf (" Could not open file %s" , file_name).str ());
2044
- if (fwrite (pixBuffer, 1 , NUMBYTES, fp) != NUMBYTES)
2045
- {
2046
- fclose (fp);
2047
- throw Py::RuntimeError (
2048
- Printf (" Error writing to file %s" , file_name).str ());
2037
+ if ((py_file = npy_PyFile_OpenFile (py_fileobj.ptr (), (char *)" w" )) == NULL ) {
2038
+ throw Py::Exception ();
2049
2039
}
2040
+ close_file = true ;
2050
2041
}
2051
- #if PY3K
2052
- else if (fd != -1 )
2042
+ else
2053
2043
{
2054
- if (write (fd, pixBuffer, NUMBYTES) != (ssize_t )NUMBYTES)
2055
- {
2056
- throw Py::RuntimeError (" Error writing to file" );
2057
- }
2044
+ py_file = py_fileobj.ptr ();
2058
2045
}
2059
- # else
2060
- else if (PyFile_CheckExact (py_fileobj. ptr ( )))
2046
+
2047
+ if ((fp = npy_PyFile_Dup (py_file, ( char *) " w " )))
2061
2048
{
2062
- fp = PyFile_AsFile (py_fileobj.ptr ());
2063
2049
if (fwrite (pixBuffer, 1 , NUMBYTES, fp) != NUMBYTES)
2064
2050
{
2051
+ npy_PyFile_DupClose (py_file, fp);
2052
+
2053
+ if (close_file) {
2054
+ npy_PyFile_CloseFile (py_file);
2055
+ Py_DECREF (py_file);
2056
+ }
2057
+
2065
2058
throw Py::RuntimeError (" Error writing to file" );
2066
2059
}
2060
+
2061
+ npy_PyFile_DupClose (py_file, fp);
2062
+
2063
+ if (close_file) {
2064
+ npy_PyFile_CloseFile (py_file);
2065
+ Py_DECREF (py_file);
2066
+ }
2067
2067
}
2068
- #endif
2069
2068
else
2070
2069
{
2071
2070
PyObject* write_method = PyObject_GetAttrString (py_fileobj.ptr (),
0 commit comments