Skip to content

Commit d832c1e

Browse files
committed
Initializing PyModuleDef object with PyModuleDef_HEAD_INIT.
Python 3.8 documentation: m_base - Always initialize this member to PyModuleDef_HEAD_INIT. Long-standing (since first github commit in 2015), inconsequential bug. Also removing inconsequential Py_INCREF(def): PyModule_Create() resets the reference count to 1.
1 parent fafd9b4 commit d832c1e

File tree

2 files changed

+15
-8
lines changed

2 files changed

+15
-8
lines changed

include/pybind11/detail/common.h

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -308,11 +308,11 @@ extern "C" {
308308
}
309309
\endrst */
310310
#if PY_MAJOR_VERSION >= 3
311-
#define PYBIND11_MODULE_PY2_VS_PY3_SPECIFIC(name) \
311+
#define PYBIND11_MODULE_DETAIL_CREATE(name) \
312312
static PyModuleDef mdef; \
313313
auto m = pybind11::module(PYBIND11_TOSTRING(name), nullptr, &mdef);
314314
#else
315-
#define PYBIND11_MODULE_PY2_VS_PY3_SPECIFIC(name) \
315+
#define PYBIND11_MODULE_DETAIL_CREATE(name) \
316316
auto m = pybind11::module(PYBIND11_TOSTRING(name));
317317
#endif
318318
#define PYBIND11_MODULE(name, variable) \
@@ -321,7 +321,7 @@ extern "C" {
321321
PYBIND11_PLUGIN_IMPL(name) { \
322322
PYBIND11_CHECK_PYTHON_VERSION \
323323
PYBIND11_ENSURE_INTERNALS_READY \
324-
PYBIND11_MODULE_PY2_VS_PY3_SPECIFIC(name) \
324+
PYBIND11_MODULE_DETAIL_CREATE(name) \
325325
try { \
326326
PYBIND11_CONCAT(pybind11_init_, name)(m); \
327327
return m.ptr(); \

include/pybind11/pybind11.h

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -857,13 +857,20 @@ class module : public object {
857857
PYBIND11_OBJECT_DEFAULT(module, object, PyModule_Check)
858858

859859
/// Create a new top-level Python module with the given name and docstring
860+
#if PY_MAJOR_VERSION >= 3
860861
explicit module(const char *name, const char *doc = nullptr, PyModuleDef *def = nullptr) {
861862
if (!def) def = new PyModuleDef();
862-
std::memset(def, 0, sizeof(PyModuleDef));
863-
def->m_name = name;
864-
def->m_doc = options::show_user_defined_docstrings() ? doc : nullptr;
865-
def->m_size = -1;
866-
Py_INCREF(def);
863+
def = new (def) PyModuleDef { // Placement new (not an allocation).
864+
/* m_base */ PyModuleDef_HEAD_INIT,
865+
/* m_name */ name,
866+
/* m_doc */ options::show_user_defined_docstrings() ? doc : nullptr,
867+
/* m_size */ -1,
868+
/* m_methods */ nullptr,
869+
/* m_slots */ nullptr,
870+
/* m_traverse */ nullptr,
871+
/* m_clear */ nullptr,
872+
/* m_free */ nullptr
873+
};
867874
m_ptr = PyModule_Create(def);
868875
#else
869876
explicit module(const char *name, const char *doc = nullptr) {

0 commit comments

Comments
 (0)