Skip to content

Commit d9f03b7

Browse files
committed
static allocation for PyModuleDef, to avoid leak check errors.
Trying a different approach to pybind#2019. EXPERIMENTAL, PROOF OF CONCEPT, please do not review. If this approach works out additional work is needed to avoid code duplication.
1 parent 04fdc44 commit d9f03b7

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

include/pybind11/detail/common.h

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,22 @@ extern "C" {
306306
});
307307
}
308308
\endrst */
309+
#if PY_MAJOR_VERSION >= 3
310+
#define PYBIND11_MODULE(name, variable) \
311+
PYBIND11_MAYBE_UNUSED \
312+
static void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &); \
313+
PYBIND11_PLUGIN_IMPL(name) { \
314+
PYBIND11_CHECK_PYTHON_VERSION \
315+
PYBIND11_ENSURE_INTERNALS_READY \
316+
static PyModuleDef mdef; \
317+
auto m = pybind11::module(PYBIND11_TOSTRING(name), nullptr, &mdef); \
318+
try { \
319+
PYBIND11_CONCAT(pybind11_init_, name)(m); \
320+
return m.ptr(); \
321+
} PYBIND11_CATCH_INIT_EXCEPTIONS \
322+
} \
323+
void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &variable)
324+
#else
309325
#define PYBIND11_MODULE(name, variable) \
310326
PYBIND11_MAYBE_UNUSED \
311327
static void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &); \
@@ -319,6 +335,7 @@ extern "C" {
319335
} PYBIND11_CATCH_INIT_EXCEPTIONS \
320336
} \
321337
void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &variable)
338+
#endif
322339

323340

324341
PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)

include/pybind11/pybind11.h

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -827,10 +827,14 @@ class module : public object {
827827
PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
828828

829829
/// Create a new top-level Python module with the given name and docstring
830+
#if PY_MAJOR_VERSION >= 3
831+
explicit module(const char *name, const char *doc = nullptr, PyModuleDef *def = nullptr) {
832+
#else
830833
explicit module(const char *name, const char *doc = nullptr) {
834+
#endif
831835
if (!options::show_user_defined_docstrings()) doc = nullptr;
832836
#if PY_MAJOR_VERSION >= 3
833-
PyModuleDef *def = new PyModuleDef();
837+
if (!def) def = new PyModuleDef();
834838
std::memset(def, 0, sizeof(PyModuleDef));
835839
def->m_name = name;
836840
def->m_doc = doc;

0 commit comments

Comments
 (0)