[C++-sig] return_internal_reference & overriding methods in a class.

Nicolas Lara nicolaslara at gmail.com
Thu Jun 25 05:31:43 CEST 2009


Hello,

I'm having trouble trying to override a method on a class exposed to
Python. I cannot modify the original class, so I need to wrap it to
change the behaviour of some methods to be Python compatible. The
classes look like the following:

struct DocumentWrap : Document, wrapper<Document>
{
  DocumentWrap() : Document(){ };
  DocumentWrap(const Document&) { };
  wstring toString()
  {
    wstring w(_T("test"));
    return w;
  }
  int test(){
    return 1;
  }
};

  class_<Hits>("Hits", init<int>())
    .def("doc", &Hits::doc, return_internal_reference<>());
  class_<DocumentWrap>("Document")
    .def("toString", &DocumentWrap::toString)
    .def("test", &DocumentWrap::test)
    ;

Hits::doc returns a Document. If I do:

>>> d = Document()
>>> d.test()
1
>>> d.toString()
"test"

I get the right answer. However, If I obtain the class through Hits I
get a reference to a c++ object of type Document (not DocumentWrap) so
trying to execute the methods yield:

Traceback (most recent call last):
  File "t.py", line 10, in <module>
    d.test()
Boost.Python.ArgumentError: Python argument types in
    Document.test(Document)
did not match C++ signature:
    test(DocumentWrap {lvalue})

Traceback (most recent call last):
  File "t.py", line 10, in <module>
    d.toString()
Boost.Python.ArgumentError: Python argument types in
    Document.toString(Document)
did not match C++ signature:
    toString(DocumentWrap {lvalue})

Is there any way to get python to understand the internal reference to
Document can be treated as a DocumentWrap?

Thanks in advance!

Best Regards,

-- 
Nicolas Lara
Linux user #380134
http://nicolas-lara.blogspot.com/
Public key id: 0x152e7713 at http://subkeys.pgp.net/


More information about the Cplusplus-sig mailing list