O
O
Ockonal2012-07-18 21:13:08
Python
Ockonal, 2012-07-18 21:13:08

Boost.python and pointers

Greetings. There is this code:

class Foo()
{
   virtual void Print() = 0;
};

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

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

    // Экспорт
    bp::class_<FooWrap, boost::noncopyable>("Foo")
        .def("Print", bp::pure_virtual(&Foo::Print))
    bp::def("ProcessFoo", &ProcessFoo);


I have a base class, I am exporting it to python via the boost.python library. There is also a function that takes a pointer to this class.

When I try to do this in python:

class NewFoo(Foo):
   def Print():
      print 'Print call'

ProcessFoo( NewFoo() )


Segfault - the debugger shows what crashes on a call to the Print function.

It is logical to assume that on the C++ side there is already an invalid pointer, most likely. Maybe you need to somehow specify something through policy? Or is it simply impossible to pass a class object as a pure pointer in c++?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladislav, 2012-07-19
@Ockonal

To be honest, I have never used this thing, but for the sake of interest I decided to try it.
And ... everything worked (taking into account minor code corrections for "compilability").
hello.cpp:

#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 ) ;
}

hello.py:
import hello_ext
 
class  NewFoo ( hello_ext. Foo ) :
   def Print ( self ) :
      print  'Print call'
 
hello_ext. ProcessFoo (  NewFoo ( )  )

Launch:
E:Temppython>"d:/Coding/Python 2.7/python.exe" hello.py
Print call

Those. data:
boost 1.43
MSVS 2010 SP1
python 2.7
compiled with bjam

V
Vladislav, 2012-07-19
@Wyrd

Assumption: the wrong adapter is clinging (meaning something like boost_python-vc100-mt-gd-1_43.dll). Perhaps you have her name without a version (you can set the boost like this)? maybe you updated the boost and did not rebuild the lib?
Assumption 2 (doubtful): Is the C++ part compiled for the wrong python that is being run?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question