Memory Management in Embedded Python

"Martin v. Löwis" martin at v.loewis.de
Thu Jan 18 19:25:34 CET 2007


Huayang Xia schrieb:
> I have a piece of code like this:
> 
>       void funct(PyObject* pyobj)
>       {
>          char   str[128];
>          strncpy(str, "just a test string", sizeof(str));
>          PyObject* pydata = PyObject_CallMethod(pyobj, "method_x",
> "s", str);
>          Py_DECREF(pydata);
>       }
> 
> After the function is exited, the str is not there anymore. Will this
> affect python operation. How does python use the str? It's copied or it
> just uses the pointer?

The interpreter creates a string object, and passes that to method_x.
Creating a string object does indeed create a copy. The string object
will be refcounted, so it exists as long as there is a reference to it.
Likely (unless the method_x implementation somehow stores the string),
it gets deallocated before PyObject_Call returns.

HTH,
Martin



More information about the Python-list mailing list