1

私のアプリケーションでは、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
4

3 に答える 3

0

Python オブジェクトを保持し、Boost を使用して通知するラッパー クラスを作成する必要がありますhas_back_reference

http://www.boost.org/doc/libs/1_55_0/libs/python/doc/v2/has_back_reference.html

于 2015-01-21T12:16:36.873 に答える
0

次のように定義する必要があります。

class_<Apple>("Apple", no_init)
    .def("__init__", make_constructor(getMoldyApple))
;
于 2014-01-16T07:56:34.903 に答える