私のアプリケーションでは、boost::shared_ptr から boost::python を介して C++ オブジェクトをラップしています。
私が抱えている問題は、C++ で参照を返すたびに、boost が既存の Python オブジェクトを再利用する代わりに、参照を指す新しいオブジェクトを割り当てることです。とりわけ、これは Python で設定された可能性がある等値テストとカスタム プロパティを壊します。
同じ基礎となるオブジェクトを指す shared_ptr を与えるたびに、既存の boost::python::object (または少なくとも PyObject) を自動的に再利用するために boost::python を取得するクリーンで簡単な方法はありますか?
コード例:
C++:
#include <boost/python.hpp>
using namespace boost::python;
class Apple {};
boost::shared_ptr<Apple> theMoldyApple(new Apple());
boost::shared_ptr<Apple> getMoldyApple() {
//pretend we do some logic here that won't always return theMoldyApple
//exactly
return theMoldyApple;
}
BOOST_PYTHON_MODULE(bobtest) {
class_<Apple, boost::shared_ptr<Apple>>("Apple", init<>());
def("getMoldyApple", getMoldyApple);
}
パイソン:
from bobtest import *
# Set a custom property on the Python object:
ma = getMoldyApple()
ma.customProp = 11
# This works fine because ma is the same PyObject is was above:
print "ma.customProp:", ma.customProp
# This doesn't work because boost::python wraps a copy of the shared_ptr
# (that points to theMoldyApple) with a new PyObject each time I call
# getMoldyApple()
print "getMoldyApple().customProp:", getMoldyApple().customProp
結果:
ma.customProp: 11
getMoldyApple().customProp:
Traceback (most recent call last):
File "<string>", line 14, in <module>
AttributeError: 'Apple' object has no attribute 'customProp'
望ましい結果:
ma.customProp: 11
getMoldyApple().customProp: 11