From dd57a34e2d653478bf0b6f3d54c7c0cae46f3364 Mon Sep 17 00:00:00 2001 From: Wenzel Jakob Date: Sat, 26 Dec 2015 14:04:52 +0100 Subject: [PATCH] improved error handling at module import time --- include/pybind11/common.h | 16 ++++++++++++++-- include/pybind11/pybind11.h | 5 ++++- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/include/pybind11/common.h b/include/pybind11/common.h index d26c84f8..bebcd072 100644 --- a/include/pybind11/common.h +++ b/include/pybind11/common.h @@ -67,12 +67,24 @@ #endif #if PY_MAJOR_VERSION >= 3 -#define PYBIND11_PLUGIN(name) \ +#define PYBIND11_PLUGIN_IMPL(name) \ extern "C" PYBIND11_EXPORT PyObject *PyInit_##name() #else -#define PYBIND11_PLUGIN(name) \ +#define PYBIND11_PLUGIN_IMPL(name) \ extern "C" PYBIND11_EXPORT PyObject *init##name() #endif +#define PYBIND11_PLUGIN(name) \ + static PyObject *pybind11_init(); \ + PYBIND11_PLUGIN_IMPL(name) { \ + try { \ + return pybind11_init(); \ + } catch (const std::exception &e) { \ + PyErr_SetString(PyExc_ImportError, e.what()); \ + return nullptr; \ + } \ + } \ + PyObject *pybind11_init() + NAMESPACE_BEGIN(pybind11) diff --git a/include/pybind11/pybind11.h b/include/pybind11/pybind11.h index eb0bf206..c159b11a 100644 --- a/include/pybind11/pybind11.h +++ b/include/pybind11/pybind11.h @@ -471,7 +471,10 @@ public: } static module import(const char *name) { - return module(PyImport_ImportModule(name), false); + PyObject *obj = PyImport_ImportModule(name); + if (!obj) + throw std::runtime_error("Module \"" + std::string(name) + "\" not found!"); + return module(obj, false); } };