Skip to content

Commit d9f0605

Browse files
jcpunkstefanseefeld
authored andcommitted
Convert Python 3.1+ to use public C API for filenames
1 parent 9ad5298 commit d9f0605

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

src/exec.cpp

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -104,14 +104,22 @@ object BOOST_PYTHON_DECL exec_file(char const *filename, object global, object l
104104
if (local.is_none()) local = global;
105105
// should be 'char const *' but older python versions don't use 'const' yet.
106106
char *f = const_cast<char *>(filename);
107-
// Let python open the file to avoid potential binary incompatibilities.
108-
#if PY_VERSION_HEX >= 0x03040000
109-
FILE *fs = _Py_fopen(f, "r");
107+
#if PY_VERSION_HEX >= 0x03010000
108+
// Let python manage any UTF bits to avoid potential incompatibilities.
109+
PyObject *fo = Py_BuildValue("s", f);
110+
PyObject *fb = Py_None;
111+
PyUnicode_FSConverter(fo, &fb);
112+
f = PyBytes_AsString(fb);
113+
FILE *fs = fopen(f, "r");
114+
Py_DECREF(fo);
115+
Py_DECREF(fb);
110116
#elif PY_VERSION_HEX >= 0x03000000
117+
// Let python open the file to avoid potential binary incompatibilities.
111118
PyObject *fo = Py_BuildValue("s", f);
112-
FILE *fs = _Py_fopen(fo, "r");
119+
FILE *fs = _Py_fopen(fo, "r"); // Private CPython API
113120
Py_DECREF(fo);
114121
#else
122+
// Let python open the file to avoid potential binary incompatibilities.
115123
PyObject *pyfile = PyFile_FromString(f, const_cast<char*>("r"));
116124
if (!pyfile) throw std::invalid_argument(std::string(f) + " : no such file");
117125
python::handle<> file(pyfile);

0 commit comments

Comments
 (0)