0

我有 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);
}

编译就OK了。但是当我调用 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 转换为 char 放置在派生类 c++ 代码中:

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 方法的包装不好,所以任何帮助都将不胜感激。谢谢你。

4

1 回答 1

0

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

于 2013-02-07T07:46:16.057 回答