派生类方法的Boost :: python包装器

时间:2013-01-02 03:30:12

标签: python boost wrapper derived

我有C ++类及其对boost :: python:

的包装器
class CApp
{
 public:
   virtual bool FOOs (){}; //does not matter for now
   bool Run( const char * First,const char * Last) 
   {
     ...
     return "Running..."
   };

struct pyApp : CApp, wrapper<CApp>  //derived class 
{
   ... // wrappers for virtual methods
}

#include <boost/python.hpp>
using namespace boost::python;
BOOST_PYTHON_MODULE( myApp )
{
class_<pyApp, boost::noncopyable>("CApp", init<>()   )
            ...
    .def("Run",&pyMOOSApp::Run);
}

编译没问题。但是当我调用Python代码时

from myApp import *

class pyApp(CApp):
def __init__(self):
    print "INIT-->"

CClass = CApp()
pyClass = pyApp()
CClass.Run('myApp','bar')
pyClass.Run('myApp','bar')

我有一个错误:

INIT-->
Running... // this is from CClass.Run
Traceback (most recent call last):
File "./pytest.py", line 18, in <module>
pyClass.Run('myApp','bar')
Boost.Python.ArgumentError: Python argument types in
CApp.Run(pyApp, str, str)
did not match C++ signature:
Run(CApp {lvalue}, char const*, char const*)

所以我试图为Run方法编写一个包装器,它将str转换为放在派生类c ++代码中的char:

bool Run(std::string a, std::string b) {
    char * cstrA;
    char * cstrB;
    cstrA = new char[a.size()+1];
    cstrB = new char[b.size()+1];
    strcpy(cstrA,a.c_str());
    strcpy(cstrB,b.c_str());
    return this -> CApp::Run(cstrA, cstrB);
}

但唯一的变化是在最后一击:

did not match C++ signature:
Run(pyApp {lvalue}, std::string, std::string)

我很确定一个包含Run方法的错误包装,所以任何帮助都会受到赞赏。 谢谢。

1 个答案:

答案 0 :(得分:0)

我刚看到你的另一个问题(Using derived class (C++) by Python BOOST),并相信这有同样的解决方案。如果在派生类中提供init,则需要在基类上调用init()。请在此处查看我的解决方案 - https://stackoverflow.com/a/14742937/82896