Popular C++ recipes tagged "extending"http://code.activestate.com/recipes/langs/cpp/tags/extending/2011-12-19T15:24:03-08:00ActiveState Code RecipesAutomatic Python PyObject ref-count management in C++ using a smart ptr (C++) 2011-12-19T15:24:03-08:00samhhttp://code.activestate.com/recipes/users/4180289/http://code.activestate.com/recipes/577985-automatic-python-pyobject-ref-count-management-in-/ <p style="color: grey"> C++ recipe 577985 by <a href="/recipes/users/4180289/">samh</a> (<a href="/recipes/tags/extending/">extending</a>). </p> <p>Managing ref-counting is a complex and error prone business. If you choose C++ to extend or embed Python, you can simply use a modification on <code>std::auto_ptr</code>. Instead of calling delete on the managed pointer, it will decref it.</p> <p>So now you can do:</p> <pre class="prettyprint"><code>auto_pyptr pyHelloStr(PyStr_FromString("Hello World!")); </code></pre> <p>and forget about having to decref it altogether! Just like <code>auto_ptr</code> you can get the <code>PyObject *</code> with <code>get()</code>, release it from managed control with <code>release()</code>, and rebind it with <code>reset(new_ptr)</code>. You can also incref it by calling <code>inc()</code>, but be cautious as you can easily create a leak by increfing once to much.</p>