[C++-sig] Copying objects derived in python from C++?

Mark Williams mark at image-engine.com
Wed Jun 6 22:35:26 CEST 2007


I have a short example below which demonstrates and issue I'm having.

I have a base class, "Base", written in C++ and exposed via boost.python.

I have class, "Derived", which is written in Python and derives from the 
C++ base.

In addition, there is a simple C++ function "func" which takes a Base* 
as an argument.

What I'd like to be able to do is take a copy of an instance of the 
derived class, within Python, and pass it into the C++ function. 
However, this yields an ArgumentError exception:

Boost.Python.ArgumentError: Python argument types in
    MyModule.func(Derived)
did not match C++ signature:
    func(boost::shared_ptr<Base>)

So it would appear that in taking a copy of the instance using Python's 
"copy.copy", I'm losing the C++ portion of the object. What is the 
correct way to go about doing this, please?

Here's the test case I'm using:

================ C++ ============

struct Base
{
    Base(){}
};
typedef boost::shared_ptr<Base> BasePtr;

void func( BasePtr b )
{
    std::cerr << "func(" << b.get() << ")" << std::endl;
}

BOOST_PYTHON_MODULE(MyModule)
{
    class_<Base, BasePtr>("Base", no_init)
        .def(init<>())
    ;
   
    def("func", func);

}

================ Python ============

import copy
from MyModule import *

class Derived(Base):
    pass

b = Base()
func(b)

d = Derived()
func(d)

d_copy = copy.copy(d)
func(d_copy)

============ Example output ==============

func(0x9db3500)
func(0x9d76b20)
Traceback (most recent call last):
  File "test.py", line 15, in <module>
    func(d_copy)
Boost.Python.ArgumentError: Python argument types in
    MyModule.func(Derived)
did not match C++ signature:
    func(boost::shared_ptr<Base>)







Thanks in advance,

Mark



More information about the Cplusplus-sig mailing list