[C++-sig] How to wrap method taking ownership of a raw pointer to an _abstract_ Class

Dennis Brakhane Dennis.Brakhane at urz.uni-heidelberg.de
Mon Sep 26 18:51:01 CEST 2005


Hello list.

I have a method with the following signature:
void Bar::set(Foo* foo)

The method takes ownership of Foo*; however, unlike the example in the 
FAQ, Foo is an abstract Base class. Now, if I try to wrap it similary to 
the FAQ example:

-------8<--------------8<------------

#include <iostream>
using namespace std;

struct Foo
{
     Foo() {cerr << "created" << endl;}
     virtual ~Foo() {cerr << "destroyed" << endl;}
     virtual void Baz() = 0;
};

struct Bar
{
     void s(Foo* f)
	{
	    fp = f;
	}

     ~Bar()
	{
	    delete fp;
	}
private:
     Foo* fp;

};


#include <boost/python.hpp>

using namespace boost::python;

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

};

void Bar_s(Bar& b, std::auto_ptr<Foo> f)
{
     b.s(f.get());
     f.release();
}

BOOST_PYTHON_MODULE(mod)
{
     class_<FooWrap,std::auto_ptr<FooWrap>,boost::noncopyable>("Foo")
	.def("FICKEN", pure_virtual(&Foo::Baz))
	;
     class_<Bar>("Bar")
	.def("s", &Bar_s)
	;
}

-------8<--------------8<------------

It does not work in python:
 >>> import mod
 >>> class Baz(mod.Foo): pass
 >>> a = Baz()
 >>> b = Bar()
 >>> b.s(a)
Python argument types in
     Bar.s(Bar, Baz)
did not match C++ signature:
     s(Bar {lvalue}, std::auto_ptr<Foo>)



If I change std::auto_ptr<FooWrap> to std::auto_ptr<Foo>, I cannot compile:
/usr/include/boost/python/object/pointer_holder.hpp:128: error: invalid 
conversion from 'Foo*' to 'FooWrap*'

Any suggestions?

Thanks in advance,
   Dennis



More information about the Cplusplus-sig mailing list