Automatic ref-count management in C++ using a smart ptr,ref-countptr,Managing ref
Automatic ref-count management in C++ using a smart ptr,ref-countptr,Managing ref
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 std::auto_ptr.Instead of calling delete on the managed pointer, it will decref it.
So now you can do:
auto_py str = PyStr_FromString("Hello World!");
and forget about having to decref it altogether! Just like auto_ptr you canget the PyObject * with get(), release it from managed control with release(),and rebind it with reset(new_ptr). You can also incref it by calling inc(),but be cautious as you can easily create a leak by increfing once to much.
#include <memory>typedef std::auto_ptr<PyObject> auto_py_base;class auto_py : public auto_py_base {public: auto_py(PyObject * obj = NULL) : auto_py_base(obj) { } ~auto_py() { reset(); } void reset(PyObject * obj = NULL) { if(obj != get()) { PyObject * old = release(); // Avoid the delete call Py_XDECREF(old); auto_py_base::reset(obj); } } void inc() { PyObject * ptr = get(); if(ptr) Py_INCREF(ptr); }};
You can do most of this with boost::python, but that library doesn't give youfull access to the Python C API, so when you need to pass around PyObjectpointers this comes in handy.
相关内容
- python判断文件和文件夹是否存在,python判断,python判断文
- python使用urllib访问url,pythonurlliburl,python使用urll
- Python使用split使用多个字符分隔字符串,pythonsplit,Pyth
- python使用gc.get_objects()查看运行时对象,,从python2.2开始
- Python计算单词距离代码,python计算单词,#!/usr/bin/e
- Python处理gzip压缩过的网页,python处理gzip压缩,大多数网
- Python判断一个数字是否为素数,python素数,如下代码判断
- python urllib2使用ProxyHandler通过代理访问网页,,在urllib
- python webpy 输出json响应,webpyjson,webpy输出json首
- webpy获得用户post或者get的数据,上传文件示例,webpyp
评论关闭