When a cpp_function is GCed, release any memory allocated by pybind11
| 892 | |
| 893 | /// When a cpp_function is GCed, release any memory allocated by pybind11 |
| 894 | static void destruct(detail::function_record *rec, bool free_strings = true) { |
| 895 | // If on Python 3.9, check the interpreter "MICRO" (patch) version. |
| 896 | // If this is running on 3.9.0, we have to work around a bug. |
| 897 | #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9 |
| 898 | static bool is_zero = Py_GetVersion()[4] == '0'; |
| 899 | #endif |
| 900 | |
| 901 | while (rec) { |
| 902 | detail::function_record *next = rec->next; |
| 903 | if (rec->free_data) { |
| 904 | rec->free_data(rec); |
| 905 | } |
| 906 | // During initialization, these strings might not have been copied yet, |
| 907 | // so they cannot be freed. Once the function has been created, they can. |
| 908 | // Check `make_function_record` for more details. |
| 909 | if (free_strings) { |
| 910 | std::free(rec->name); |
| 911 | std::free(rec->doc); |
| 912 | std::free(rec->signature); |
| 913 | for (auto &arg : rec->args) { |
| 914 | std::free(const_cast<char *>(arg.name)); |
| 915 | std::free(const_cast<char *>(arg.descr)); |
| 916 | } |
| 917 | } |
| 918 | for (auto &arg : rec->args) { |
| 919 | arg.value.dec_ref(); |
| 920 | } |
| 921 | if (rec->def) { |
| 922 | std::free(const_cast<char *>(rec->def->ml_doc)); |
| 923 | // Python 3.9.0 decref's these in the wrong order; rec->def |
| 924 | // If loaded on 3.9.0, let these leak (use Python 3.9.1 at runtime to fix) |
| 925 | // See https://github.com/python/cpython/pull/22670 |
| 926 | #if !defined(PYPY_VERSION) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 9 |
| 927 | if (!is_zero) { |
| 928 | delete rec->def; |
| 929 | } |
| 930 | #else |
| 931 | delete rec->def; |
| 932 | #endif |
| 933 | } |
| 934 | delete rec; |
| 935 | rec = next; |
| 936 | } |
| 937 | } |
| 938 | |
| 939 | /// Main dispatch logic for calls to functions bound using pybind11 |
| 940 | static PyObject * |