我有一个 C++ 函数来解析 python 字符串:
std::string parse_string(PyObject* py_string) {
std::string out;
if (!PyString_Check(py_string)) {
PyErr_SetString(PyExc_TypeError,"expected a string");
return out;
}
out = PyString_AsString(py_string);
return out;
}
我正在从 python 包装器中调用该函数:
PyObject* some_func(PyObject* self, PyObject* args) {
// ...
std::string my_first_string = parse_string(first_py_string);
if (PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError,"more verbose error for this string");
return 0;
}
std::string my_second_string = parse_string(second_py_string);
if (PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError,"some other error for this string");
return 0;
}
// ...
}
这将根据需要引发 python 异常,但我担心PyErr_SetString
再次调用以提供更详细的消息。会不会造成泄漏?