【问题标题】:Using derived class (C++) by Python BOOST通过 Python BOOST 使用派生类 (C++)
【发布时间】:2012-12-14 03:26:59
【问题描述】:

我有想要在 Python 中使用的 C++ 类:

#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.so 文件要在 Python 中导入。 所以问题从 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})

【问题讨论】:

    标签: c++ python boost derived-class


    【解决方案1】:

    如果您在派生类中实现 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-16
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-11
      • 2023-03-25
      • 1970-01-01
      相关资源
      最近更新 更多