简体   繁体   中英

Using derived class (C++) by Python BOOST

I have C++ class that i want to use in Python:

#include "ExtraClass.h"
class CApp
{
   ...
   ExtraClass Bar; //there is function Foo()
}

BOOST_PYTHON_MODULE( CApp )
{
class_<ExtraClass>("ExtraClass",init<>())
    .def("Foo",&ExtraClass::Foo)
    ;
    class_<CApp>("CApp", init<>()) 
    .def_readonly("Bar", &CApp::Bar)
    ;

Compiling is ok. So I have CApp.so file to import in Python. So the problem begins in Python:

from CApp import *
class pyApp(CApp):
def __init__(self):
    print "<--INIT-->"
CApp = CApp()
pyApp = pyApp()
print CApp.Bar.Foo()
print pyApp.Bar.Foo()

Output:

<--INIT-->
FOO // <- this is from CApp.Bar.Foo()
Traceback (most recent call last):
  File "./pytest.py", line 16, in <module>
print pyApp.Bar.Foo()
Boost.Python.ArgumentError: 
Python argument types in None.None(pyApp) 
did not match C++ signature: None(CApp {lvalue})

If you implement a init () in the derived class then you need to be sure to call the base init () otherwise it will not have the base members.

from CApp import *
class pyApp(CApp):
def __init__(self):
    CApp.__init__(self)
    print "<--INIT-->"
CApp = CApp()
pyApp = pyApp()
print CApp.Bar.Foo()
print pyApp.Bar.Foo()

I was running into the same issue and found the solution thanks here - https://stackoverflow.com/a/6396839 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM