通过Python BOOST使用派生类(c++)

Using derived class (C++) by Python BOOST

本文关键字:c++ 派生 Python BOOST 通过      更新时间:2023-10-16

我有一个c++类,我想在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)
    ;

可以编译。这是CApp。在Python中导入的so文件。所以问题从Python开始:

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

<--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})

如果在派生类中实现init(),则需要确保调用基类init(),否则它将没有基类成员。

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()

我遇到了同样的问题,并找到了解决方案,感谢这里- https://stackoverflow.com/a/6396839.