[C++-sig] Boost.Python - Simple Pointer Question

David Abrahams dave at boost-consulting.com
Tue Jan 7 00:45:00 CET 2003


"CLARKE,RON (HP-Vancouver,ex1)" <ron_clarke at hp.com> writes:

> I know I've missed something that should be obvious and simple, but ...
> We have a medium-sized Python/C++ project and I am investigating replacing
> SWIG with Boost.Python (V2). I've read all the documentation more than once,
> reviewed the examples, etc. but I still don't see the syntax/macros/commands
> needed to allow Python to understand a pointer to an existing C++ class
> contained within another class.   Here is a simplified scenario:
>  
> class car
> {
> public:
>     car(void);
>     virtual ~car(void);
> private:
> ... 
> };
>  
> class garage{
> public:
>     garage(void);
>     ~garage(void);
>     car* pCar;
> };
>  
> Class garage contains a public pointer to a car object (I don't have the
> option of changing the C++ code; it would negatively affect too many users).
> I can create garage and car objects OK and Python understands each one:
> c=car()
> g=garage()
>  
> However, if I try something like this:
>          g.pCar = car()
> the resulting object is null and trying to simply print the object yields a
> "TypeError: bad argument for built-in operation".
>  
> What have I missed? Can someone please provide an example (other than what
> is in the documentation)?

I think this might work for you:

     class_<garage>("garage")
        .add_property(
            make_getter(&garage::pCar, with_custodian_and_ward<1,2>())
            , make_setter(&garage::pCar, return_internal_reference<>()))

However, if garage::~garage() does "delete pCar" you're going to have
big problems.  Let me know if that's the case and we can try something
else.

> Similarly, if I want to pass a pointer to a C++ object as a parameter to a
> C++ function or method, how do I expose the function properly such that a
> user can type the function call in Python and have the object properly
> passed into the C++ module?
> For example: 
>      garage.parkTheCar(c)  ## what is the proper Boost.Python syntax for
> exposing the parkTheCar method and pointer parameter?

You don't need to do anything special as long as there are no
ownership/lifetime issues in parkTheCar.  If it just uses the pointer
you pass and forgets it, you're fine.  Otherwise you might need some
CallPolicies.

    .def("parkTheCar", &garage::parkTheCar)

-- 
                       David Abrahams
   dave at boost-consulting.com * http://www.boost-consulting.com
Boost support, enhancements, training, and commercial distribution





More information about the Cplusplus-sig mailing list