diff --git a/util/RTCContext.cpp b/util/RTCContext.cpp index e683828..1c1c3ea 100644 --- a/util/RTCContext.cpp +++ b/util/RTCContext.cpp @@ -335,11 +335,15 @@ void RTCContext::onAudioProcess(const char* roomId, const char* peerId, // 7. 执行回调 if (!pyCallback_.is_none()) { std::cout << "[7] 准备执行Python回调..." << std::endl; + // 增加引用计数防止提前释放 + Py_INCREF(pyCallback_.ptr()); try { - // 增加引用计数防止提前释放 - Py_INCREF(pyCallback_.ptr()); std::cout << " pyCallback_ type: " << Py_TYPE(pyCallback_.ptr())->tp_name << std::endl; - std::cout << " pyCallback_ repr: " << PyObject_Repr(pyCallback_.ptr()) << std::endl; + PyObject* repr = PyObject_Repr(pyCallback_.ptr()); + if (repr) { + std::cout << " pyCallback_ repr: " << PyUnicode_AsUTF8(repr) << std::endl; + Py_DECREF(repr); // 必须手动释放 + } // 传递共享内存信息 pyCallback_( py::str(shm_name), // 共享内存名称 @@ -351,7 +355,19 @@ void RTCContext::onAudioProcess(const char* roomId, const char* peerId, ); std::cout << " after callback" << std::endl; if (PyErr_Occurred()) { - PyErr_Print(); + PyObject *type, *value, *traceback; + PyErr_Fetch(&type, &value, &traceback); + if (value) { + PyObject* str = PyObject_Str(value); + if (str) { + std::cerr << "Python Error: " << PyUnicode_AsUTF8(str) << std::endl; + Py_DECREF(str); + } + } + Py_XDECREF(type); + Py_XDECREF(value); + Py_XDECREF(traceback); + //PyErr_Print(); throw std::runtime_error("Python callback error"); } std::cout << " 回调执行成功" << std::endl; @@ -367,13 +383,16 @@ void RTCContext::onAudioProcess(const char* roomId, const char* peerId, << PyUnicode_AsUTF8(PyObject_Str(value)) << std::endl; PyErr_Restore(type, value, traceback); } + Py_DECREF(pyCallback_.ptr()); } catch (...) { std::cout << "[ERROR] 回调执行失败" << std::endl; munmap(ptr, data_size); close(fd); shm_unlink(shm_name); + Py_DECREF(pyCallback_.ptr()); throw; } + Py_DECREF(pyCallback_.ptr()); } else { std::cout << "[7] 无回调函数设置" << std::endl; }