Skip to content

Commit 664a868

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 0d0b37c commit 664a868

File tree

2 files changed

+14
-8
lines changed

2 files changed

+14
-8
lines changed

include/pybind11/detail/common.h

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -307,11 +307,11 @@ extern "C" {
307307
}
308308
\endrst */
309309
#if PY_MAJOR_VERSION >= 3
310-
#define PYBIND11_MODULE_PY2_VS_PY3_SPECIFIC(name) \
310+
#define PYBIND11_MODULE_DETAIL_CREATE(name) \
311311
static PyModuleDef mdef; \
312312
auto m = pybind11::module(PYBIND11_TOSTRING(name), nullptr, &mdef);
313313
#else
314-
#define PYBIND11_MODULE_PY2_VS_PY3_SPECIFIC(name) \
314+
#define PYBIND11_MODULE_DETAIL_CREATE(name) \
315315
auto m = pybind11::module(PYBIND11_TOSTRING(name));
316316
#endif
317317
#define PYBIND11_MODULE(name, variable) \
@@ -320,7 +320,7 @@ extern "C" {
320320
PYBIND11_PLUGIN_IMPL(name) { \
321321
PYBIND11_CHECK_PYTHON_VERSION \
322322
PYBIND11_ENSURE_INTERNALS_READY \
323-
PYBIND11_MODULE_PY2_VS_PY3_SPECIFIC(name) \
323+
PYBIND11_MODULE_DETAIL_CREATE(name) \
324324
try { \
325325
PYBIND11_CONCAT(pybind11_init_, name)(m); \
326326
return m.ptr(); \

include/pybind11/pybind11.h

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -830,11 +830,17 @@ class module : public object {
830830
#if PY_MAJOR_VERSION >= 3
831831
explicit module(const char *name, const char *doc = nullptr, PyModuleDef *def = nullptr) {
832832
if (!def) def = new PyModuleDef();
833-
std::memset(def, 0, sizeof(PyModuleDef));
834-
def->m_name = name;
835-
def->m_doc = options::show_user_defined_docstrings() ? doc : nullptr;
836-
def->m_size = -1;
837-
Py_INCREF(def);
833+
def = new (def) PyModuleDef { // Placement new (not an allocation).
834+
/* m_base */ PyModuleDef_HEAD_INIT,
835+
/* m_name */ name,
836+
/* m_doc */ options::show_user_defined_docstrings() ? doc : nullptr,
837+
/* m_size */ -1,
838+
/* m_methods */ nullptr,
839+
/* m_slots */ nullptr,
840+
/* m_traverse */ nullptr,
841+
/* m_clear */ nullptr,
842+
/* m_free */ nullptr
843+
};
838844
m_ptr = PyModule_Create(def);
839845
#else
840846
explicit module(const char *name, const char *doc = nullptr) {

0 commit comments

Comments
 (0)