4

cp:

#include <boost/python.hpp>

using namespace boost;
using namespace boost::python;

struct Foo
{
   virtual ~Foo() {}
   virtual void Print() = 0;
};

struct FooWrap : Foo, wrapper<Foo>
{
    void Print()
    {
        this->get_override("Print")();
    }
};

void ProcessFoo(Foo *obj) { obj->Print(); }

BOOST_PYTHON_MODULE(hello_ext)
{
    class_<FooWrap, boost::noncopyable>("Foo")
        .def("Print", pure_virtual(&Foo::Print));
    def("ProcessFoo", &ProcessFoo);
}

Python:

import hello_ext

class NewFoo(hello_ext.Foo):
   def Print(self):
      print 'Print call'

hello_ext.ProcessFoo( NewFoo() )

一切正常,通话中有Print call文字ProcessFoo。但我想将所有传递的指针存储为ProcessFoo

std::vector<Foo*> data;
void ProcessFoo(Foo *obj) { data.push_back(obj); obj->Print(); }

从函数指针退出后变得无效,我不能从向量中使用它。使该指针的寿命更长的最佳方法是什么?使用共享指针或告诉python不要删除对象(如果它删除它?)

4

1 回答 1

2

如果要存储此指针,则必须增加底层 python 对象(PyObject)的引用计数。为此,您必须实现您的 void ProcessFoo(Foo *obj) 以获取 python 对象而不是 C++ 对象,否则 boost::python 将在他的适应中为您剥离 python 对象,您无法再控制它的生命周期。

如果你这样做,你还必须显式地转换为你的 C++ 类型(但使用 boost::python 并没有那么麻烦)。

using namespace boost::python;
std::vector< std::pair<object, Foo&> > myVec;

void ProcessFoo(object o )
{
  Foo& x = extract<Foo&>(o);
  // ... do you add to container here, but remember, to add the object o
  // too, otherwise the refernce counter will be decremented and the object
  // may go away.
  myVec.push_back( std::make_pair( o, x ) );
}
于 2012-09-08T10:25:22.030 回答