[C++-sig] Wrap a virtual function which returns a raw pointer

Roman Yakovenko roman.yakovenko at gmail.com
Thu Dec 21 20:25:51 CET 2006


On 12/21/06, Birgir Sigurjonsson <birgir.sigurjonsson at roxar.com> wrote:
>
> Hi all.
> How can I wrap a  virtual function which returns a raw pointer
> which will be managed from C++.
>
> I am embedding Python in my C++ application and
> I have the follwoing classes that I want to wrap in boost.python:
>
>
> In the code below the virtual function ALFactory::make() returns a pointer
> to an abstract class AL which is also wrapped with boost.python.
> I want to be able to override make() in python and in the
> implementation of this function create and return a new python
> subclass of my C++ AL. The lifetime of the created object is managed
> by the ALFactory.
>
>
> class ALFactory : private boost::noncopyable {
> public:
>
>    ALFactory(const std::string& key);
>    virtual ~ALFactory();
>
>    virtual  AL* make() = 0;
>
> };
>
> class AL : private boost::noncopyable {
> public:
>    virtual ~AL();
> protected:
>    AL();
>
> };
>
> ################ Wrap classes
> class ALWrap : public AL, public boost::python::wrapper<AL> {
> public:
>    ALWrap() : AL() {}
> };
>
> class ALFactoryWrap : public ALFactory, public boost::python::wrapper<ALFactory> {
> public:
>    ALFactoryWrap(const std::string& key) : ALFactory(key) {}
>    AL* make() {
>      return this->get_override("make")();
>    }
> };
>
>
> ############
> BOOST_PYTHON_MODULE(import_framework) {
>      class_<ALWrap, boost::noncopyable>("AL")
>      ;
>
>      class_<ALFactoryWrap, boost::noncopyable>("ALFactory", init<std::string>())
>          .def("make",  pure_virtual(&ALFactory::make), return_value_policy<manage_new_object>())
>      ;
> }
> ###############
>
> #### Python module code
>
> from import_framework import AbstractLoader, AbstractLoaderFactory

What are AbstractLoader, AbstractLoaderFactory?
The class names you exposed are AL and ALFactory

> class Ascii135Loader(AbstractLoader):
>      def __init__(self):
>          print self.__init__

Here you have to call to AbstractLoader __init__ method. This is a must.
( I assume AbstractLoader is actually AL )

>
>
> class Ascii135LoaderFactory(AbstractLoaderFactory):
>      def __init__(self, key):
>          super(Ascii135LoaderFactory, self).__init__(key)

Why do you use super here?
AbstractLoaderFactory.__init__(self, key) should work.

-- 
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/



More information about the Cplusplus-sig mailing list