user2696156
user2696156

Reputation: 337

Extract c++ derived class object in boost python

I am trying to get c++ derived class object in python but i did not find any help in boost python. The question is that is this possible to that i can make object in c++ and that object will be accessable in python.

Upvotes: 1

Views: 1092

Answers (2)

Mathieu Roger
Mathieu Roger

Reputation: 76

I think I maybe had the same issue. I have a Base class and a Derived class both concrete and exposed to python.

class Base
{
public:
    virtual ~Base() {}
};

class Derived : public Base
{};

BOOST_PYTHON_MODULE(inheritance)
{
    boost::python::class_<Base>("Base") ;
    boost::python::class_<Derived, boost::python::bases<Base> >("Derived") ;
}   

Then I have an instance of Derived class seen as a Base reference and trying to pass it to python with correct converted type.

int main()
{
    Py_Initialize();
    initinheritance() ;

    boost::python::api::object main_module = boost::python::import("__main__");
    boost::python::api::object main_namespace = main_module.attr("__dict__");

    Derived derived ;
    const Base& base = derived ;

    // argh: 'base' is seen as python 'Base' class instance
    main_namespace["base"] = base ; 
    boost::python::exec("print base",main_namespace) ;

    // python 'var' is seen as python 'Derived' class instance 
    // when using C++ pointer and boost::python::ptr 
    main_namespace["var"] = boost::python::ptr(&base) ; 
    boost::python::exec("print var",main_namespace) ;


    Py_Finalize();

    return 0;
}

Execution prints :

<inheritance.Base object at 0x0042CC70>
<inheritance.Derived object at 0x0042CC38>

I had to use boost::python::ptr and a C++ pointer. It also works when having a Base* pointing to a real Base object.

Maybe it is what you need.

Upvotes: 1

doctorlove
doctorlove

Reputation: 19232

Given

class MyClass
{
public:
    void some_method();
};

In your BOOST_PYTHON_MODULE add your class and its methods e.g.

#include <boost/python.hpp>
using namespace boost::python;

BOOST_PYTHON_MODULE(test)
{
    class_<MyNamespace::MyClass>("MyClass") 
        .def("some_method", &MyNamespace::MyClass::some_method)
    ;  
}

Then call these in python

import test
myClass = test.MyClass()
myClass.some_method()

There are details here

If you want base and derived class you can do this:

class_<Base>("Base")
/*...*/
;

class_<Derived, bases<Base> >("Derived")
/*...*/
;

Upvotes: 0

Related Questions