Skip to main content
 首页 » 编程设计

python之PyErr_SetString 的字符串参数 : is it borrowed

2024年10月25日28bjzhanghao

PyErr_SetString 如何处理传入的 c 字符串?例如这样做安全吗:

{ 
  int age = 12; 
  std::stringstream ostr; ostr << "I'm " << age << " years old and what is this?"; 
  PyErr_SetString(PyExc_RuntimeError, ostr.str().c_str()); 
} 

显然 https://docs.python.org/2/c-api/exceptions.html#PyErr_SetString说它“转换为字符串对象”,但这是否必然意味着内容将被复制?

请您参考如下方法:

这样做是安全的。 Python 在返回之前复制字符串的内容。这也适用于其他 Python 字符串操作。

一般来说,只有对 Python 对象 (PyObject*) 的引用才可能被借用或窃取,除非另有特别说明,否则解释器会复制参数。