Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyErr_SetString's string argument: is it borrowed?

How does PyErr_SetString handle the passed in c-string? e.g. is it safe to do:

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

Obviously https://docs.python.org/2/c-api/exceptions.html#PyErr_SetString says that it's 'converted to a string object', but does that necessarily entail that the contents will be copied?

like image 733
user Avatar asked Jul 29 '26 05:07

user


1 Answers

It is safe to do so. Python copies the contents of the string before returning. This applies to other Python string operations as well.

In general, only references to Python objects (PyObject*) may be borrowed or stolen, and unless otherwise specifically specified, the interpreter copies the arguments.

like image 153
sterin Avatar answered Jul 30 '26 20:07

sterin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!