[C++-sig] creating an instance of a class_<> object in c++ and exporting it to python

Francois Ostiguy ostiguy at fnal.gov
Fri Aug 13 21:22:58 CEST 2004

Hi -

I am try in to do the following:

Consider a C++ class A wrapped using boost.python:

class_<A, A*, boost::noncopyable>("A", noinit)
  .def("f1", &A::f1)

>From C++,  I would like to

(1) create an instance of a wrapped object "A", initializing it using
    a  pointer to an existing instance of a C++ A object.

(2) export the python object into the namespace of an (embedded)

AFAIK boost.python does not provide a mechanism to accomplish (2),
but that seems straightforward using the Python C-API.

I am really at a loss on how to achieve (1) using boost.python. It would
seem like a useful thing to create instances of wrapped objects in
The most relevant bit of information I found is in the tutorial:

> Due to the dynamic nature of Boost.Python objects, any class_<T> may
>  also be one of these types! The following code snippet wraps the class
> (type)
>  object.

>  We can use this to create wrapped instances. Example
>  object vec345 = (
>        class_<Vec2>("Vec2", init<double, double>())
>            .def_readonly("length", &Point::length)
>            .def_readonly("angle", &Point::angle)
>        )(3.0, 4.0);
>    assert(vec345.attr("length") == 5.0);

This code does create an instance of vec345;
however, unless I misunderstand something I am under
the impression that every invocation of
class_<A> will re-register the class A.
Perhaps this is not a problem; nevertheless it
appears unnecessarily redundant and potentially error-prone
(multiple class_<A> declarations appearing in different source

Is it possible to somehow retrieve the class type of an extended
C++ class directly from the interpreter and then
create a new instance ?

Any comments or insight would be most welcome.


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