diff --git a/shared/common/PythonUtils.h b/shared/common/PythonUtils.h index 2afd1213..07e5b2c0 100644 --- a/shared/common/PythonUtils.h +++ b/shared/common/PythonUtils.h @@ -3,6 +3,8 @@ #include #include "PortPythonPointer.h" #include +#include +#include #include #include @@ -216,6 +218,52 @@ inline bool PyTuple_GetBoolean(PyObject* poArgs, int pos, bool* ret) return true; } +// Interned method-name strings: UI windows call OnUpdate/OnRender/... every frame, and +// PyObject_GetAttrString would build a fresh PyString per call. The cache is dropped through +// Py_AtExit, so a Py_Finalize/Py_Initialize cycle never sees stale objects. +struct __PyNameHash +{ + using is_transparent = void; + size_t operator()(std::string_view s) const noexcept { return std::hash{}(s); } +}; +inline std::unordered_map>& __PyNameCache() +{ + static std::unordered_map> cache; + return cache; +} +inline bool& __PyNameCacheRegistered() +{ + static bool registered = false; + return registered; +} +inline void __PyClearNameCache() +{ + // Runs inside Py_Finalize after the interpreter released its objects; only forget the pointers. + __PyNameCache().clear(); + __PyNameCacheRegistered() = false; +} +inline PyObject* __PyInternedName(const char* c_szName) +{ + auto& cache = __PyNameCache(); + auto it = cache.find(std::string_view(c_szName)); + if (it != cache.end()) + return it->second; + if (!__PyNameCacheRegistered()) + { + if (Py_AtExit(__PyClearNameCache) != 0) + return nullptr; + __PyNameCacheRegistered() = true; + } + PyObject* poName = PyString_InternFromString(c_szName); + if (!poName) + { + PyErr_Clear(); + return nullptr; + } + cache.emplace(c_szName, poName); // the cache owns this reference + return poName; +} + inline bool __PyCallClassMemberFunc_ByCString(PyObject* poClass, const char* c_szFunc, PyObject* poArgs, PyObject** ppoRet) { if (!poClass) @@ -224,7 +272,8 @@ inline bool __PyCallClassMemberFunc_ByCString(PyObject* poClass, const char* c_s return false; } - PyObject * poFunc = PyObject_GetAttrString(poClass, (char *)c_szFunc); + PyObject * poName = __PyInternedName(c_szFunc); + PyObject * poFunc = poName ? PyObject_GetAttr(poClass, poName) : PyObject_GetAttrString(poClass, (char *)c_szFunc); if (!poFunc) { PyErr_Clear();