[C++-sig] c++ to python automatic conversion

Francois Ostiguy ostiguy at fnal.gov
Mon Mar 8 21:40:27 CET 2004


Hi -

I am having difficulty with c++ to python conversion. Consider the
following snippet:

================================================================================
#include <boost/python.hpp>

using namespace boost::python;

struct B {
    int n;
    int m;
    B(): n(0), m(0) {
    }
};

struct A {

    A() {}
    B* makeB() {
      return new B;
    }
};


BOOST_PYTHON_MODULE(demo)
{

class_<A>("A")
    .def("makeB",  &A::makeB, return_value_policy<manage_new_object>() );

class_<B>("B");

}
=====================================================================================

Then, the following works fine (no error)

Python 2.3.3 (#3, Mar  8 2004, 11:58:32)
[GCC 3.3.3] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
>>> from demo import *
>>> a = A()
>>> b = a.makeB()
>>> type(b)
<class 'demo.B'>

However, if I put class A and class B in two different files (modules) say
demo1 and demo2 repectively, I get

Python 2.3.3 (#3, Mar  8 2004, 11:58:32)
[GCC 3.3.3] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
>>> from demo1 import A
>>> from demo2 import B
>>> a = A()
>>> b = a.makeB()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: No Python class registered for C++ class B

Do I have to provide an explicit converter ?
Can you explain how this can be done ?

As usual, any help is greatly appreciated.

-Francois

----------------------------------------------------------------------------
Dr. Jean-Francois OSTIGUY                              voice: (630) 840-2231
Beam Physics Dept MS220                                  FAX: (630) 840-6039
Fermi National Accelerator Laboratory                email: ostiguy at fnal.gov
Batavia IL 60510-0500                           WWW:www-ap.fnal.gov/~ostiguy





More information about the Cplusplus-sig mailing list