Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c3d39b5

Browse files
committed
Update backend_agg to use the Numpy file-handling compatibility functions.
1 parent bee6479 commit c3d39b5

File tree

1 file changed

+24
-25
lines changed

1 file changed

+24
-25
lines changed

src/_backend_agg.cpp

Lines changed: 24 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939

4040
#include "numpy/arrayobject.h"
4141
#include "agg_py_transforms.h"
42+
#include "file_compat.h"
4243

4344
#ifndef M_PI
4445
#define M_PI 3.14159265358979323846
@@ -2028,44 +2029,42 @@ RendererAgg::write_rgba(const Py::Tuple& args)
20282029

20292030
FILE *fp = NULL;
20302031
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;
20362034

20372035
if (py_fileobj.isString())
20382036
{
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();
20492039
}
2040+
close_file = true;
20502041
}
2051-
#if PY3K
2052-
else if (fd != -1)
2042+
else
20532043
{
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();
20582045
}
2059-
#else
2060-
else if (PyFile_CheckExact(py_fileobj.ptr()))
2046+
2047+
if ((fp = npy_PyFile_Dup(py_file, (char *)"w")))
20612048
{
2062-
fp = PyFile_AsFile(py_fileobj.ptr());
20632049
if (fwrite(pixBuffer, 1, NUMBYTES, fp) != NUMBYTES)
20642050
{
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+
20652058
throw Py::RuntimeError("Error writing to file");
20662059
}
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+
}
20672067
}
2068-
#endif
20692068
else
20702069
{
20712070
PyObject* write_method = PyObject_GetAttrString(py_fileobj.ptr(),

0 commit comments

Comments
 (0)