pybind / pybind11

Seamless operability between C++11 and Python
https://pybind11.readthedocs.io/
Other
15.21k stars 2.06k forks source link

NULL co_filename crashes construction of C++ exception description #2257

Closed RonAvitzur closed 4 years ago

RonAvitzur commented 4 years ago

When frame->f_code->co_filename == NULL pybind11 crashes constructing the C++ exception

Using PyBind11 on Xcode 11 on macOS, I'm seeing a runtime error in cast.h in PYBIND11_NOINLINE inline std::string error_string at handle(frame->f_code->co_filename).cast<std::string>() when co_filename is NULL as the constructed handle isn't a valid python object. This is inside of

pybind11::detail::object_api<pybind11::handle>::operator()<(pybind11::return_value_policy)1, char&>(char&) const at cast.h:2159
pybind11::detail::simple_collector<(pybind11::return_value_policy)1>::call(_object*) const at cast.h:2006
pybind11::error_already_set::error_already_set() at pytypes.h:326

My code looks something like:

py::initialize_interpreter();
py::module SymPy = py::module::import("sympy");
py::object simplify = SymPy.attr("simplify");
py::object parse = SymPy.attr("parse_expr");
try { py::object result = simplify(parse("a+1=b+1")); }
catch (...) {}

Changing cast.h to ignore NULL co_filename avoids this,

(frame->f_code->co_filename ? handle(frame->f_code->co_filename).cast<std::string>() : "")

but since I'm brand new to both Python, pybind11 and sympy and have no idea what the underlying problem is, I don't know if the bandaid on the symptom leaves a more fundamental problem lurking. The problem is solely in constructing the error string for the C++ exception, so it seems a low priority.

RonAvitzur commented 4 years ago

I just realized that my Xcode Build Settings Headers search paths pointed to /Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Headers which is the Python 3.7 included in Xcode 11, but I was compiling with a static library of Python 3.8. Oops.

My bad. "Never mind." (in SNL's Emily Litella's voice.) PEBKAC. Problem exists between keyboard and computer.