如何在Python中实现C++类,由C++调用?

2024-03-28 16:14:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个C++编写的类接口。我有几个实现这个接口的类也用C++编写。这些调用在一个较大的C++程序的上下文中,它基本上实现了“Maple”。我希望能够用Python编写这个接口的实现,并允许它们在较大的C++程序的上下文中使用,就像它们是用C++编写的一样。

关于Python和C++接口的文章很多,但我无法弄清楚如何做我想做的事情。我能找到的最接近的地方是这里:http://www.cs.brown.edu/~jwicks/boost/libs/python/doc/tutorial/doc/html/python/exposing.html#python.class_virtual_functions,但这并不完全正确。

更具体的,假设我有一个现有的C++接口定义了类似的:

// myif.h
class myif {
   public:
     virtual float myfunc(float a);
};

我想做的是:

// mycl.py
... some magic python stuff ...
class MyCl(myif):
  def myfunc(a):
    return a*2

那么,回到我的C++代码中,我想说的是:

// mymain.cc
void main(...) {
  ... some magic c++ stuff ...
  myif c = MyCl();  // get the python class
  cout << c.myfunc(5) << endl;  // should print 10
}

我希望这足够清楚;)


Tags: 程序dochtmlmagic文章virtualsomefloat
3条回答

这个答案有两部分。首先,您需要以一种允许Python实现随意重写部分内容的方式在Python中公开接口。然后,您需要显示C++程序(在{ }如何调用Python。


向Python公开现有接口:

第一部分用SWIG很容易。我稍微修改了示例场景以解决一些问题,并添加了一个额外的测试功能:

// myif.h
class myif {
   public:
     virtual float myfunc(float a) = 0;
};

inline void runCode(myif *inst) {
  std::cout << inst->myfunc(5) << std::endl;
}

现在我将在不在应用程序中嵌入Python的情况下查看这个问题,即在Python中开始使用,而不是在C++中使用{{CD2>}。不过,以后再加上这一点是相当简单的。

首先是得到cross-language polymorphism working

%module(directors="1") module

// We need to include myif.h in the SWIG generated C++ file
%{
#include <iostream>
#include "myif.h"
%}

// Enable cross-language polymorphism in the SWIG wrapper. 
// It's pretty slow so not enable by default
%feature("director") myif;

// Tell swig to wrap everything in myif.h
%include "myif.h"

为了做到这一点,我们在全球范围内启用了SWIG的director功能,特别是针对我们的界面。不过,其余的都是相当标准的饮料。

我编写了一个测试Python实现:

import module

class MyCl(module.myif):
  def __init__(self):
    module.myif.__init__(self)
  def myfunc(self,a):
    return a*2.0

cl = MyCl()

print cl.myfunc(100.0)

module.runCode(cl)

然后我就可以编译并运行这个:

swig -python  -c++ -Wall myif.i 
g++ -Wall -Wextra -shared -o _module.so myif_wrap.cxx -I/usr/include/python2.7 -lpython2.7

python mycl.py 
200.0
10

正是你希望从测试中看到的。


在应用程序中嵌入Python:

接下来我们需要实现mymain.cc的真实版本。我已经画了一幅草图:

#include <iostream>
#include "myif.h"
#include <Python.h>

int main()
{
  Py_Initialize();

  const double input = 5.0;

  PyObject *main = PyImport_AddModule("__main__");
  PyObject *dict = PyModule_GetDict(main);
  PySys_SetPath(".");
  PyObject *module = PyImport_Import(PyString_FromString("mycl"));
  PyModule_AddObject(main, "mycl", module);

  PyObject *instance = PyRun_String("mycl.MyCl()", Py_eval_input, dict, dict);
  PyObject *result = PyObject_CallMethod(instance, "myfunc", (char *)"(O)" ,PyFloat_FromDouble(input));

  PyObject *error = PyErr_Occurred();
  if (error) {
    std::cerr << "Error occured in PyRun_String" << std::endl;
    PyErr_Print();
  }

  double ret = PyFloat_AsDouble(result);
  std::cout << ret << std::endl;

  Py_Finalize();
  return 0;
}

基本上只是标准的embedding Python in another application。它的工作原理和给出的正是你希望看到的:

g++ -Wall -Wextra -I/usr/include/python2.7 main.cc -o main -lpython2.7
./main
200.0
10
10

最后一个难题是能够将在Python中创建实例得到的PyObject*转换为myif *。SWIG再一次让这变得相当简单。

首先,我们需要让SWIG在headerfile中为我们公开它的运行时。我们需要给SWIG打一个额外的电话:

swig -Wall -c++ -python -external-runtime runtime.h

接下来,我们需要重新编译SWIG模块,显式地给出SWIG知道名称的类型表,以便我们可以在main.cc中查找它。我们重新编译。因此使用:

g++ -DSWIG_TYPE_TABLE=myif -Wall -Wextra -shared -o _module.so myif_wrap.cxx -I/usr/include/python2.7 -lpython2.7

然后,我们添加一个helper函数,用于将main.cc中的PyObject*转换为myif*

#include "runtime.h"
// runtime.h was generated by SWIG for us with the second call we made

myif *python2interface(PyObject *obj) {
  void *argp1 = 0;
  swig_type_info * pTypeInfo = SWIG_TypeQuery("myif *");

  const int res = SWIG_ConvertPtr(obj, &argp1,pTypeInfo, 0);
  if (!SWIG_IsOK(res)) {
    abort();
  }
  return reinterpret_cast<myif*>(argp1);
}

现在我们可以在main()中使用它了:

int main()
{
  Py_Initialize();

  const double input = 5.5;

  PySys_SetPath(".");
  PyObject *module = PyImport_ImportModule("mycl");

  PyObject *cls = PyObject_GetAttrString(module, "MyCl");
  PyObject *instance = PyObject_CallFunctionObjArgs(cls, NULL);

  myif *inst = python2interface(instance);
  std::cout << inst->myfunc(input) << std::endl;

  Py_XDECREF(instance);
  Py_XDECREF(cls);

  Py_Finalize();
  return 0;
}

最后,我们必须用-DSWIG_TYPE_TABLE=myif编译main.cc,这给出了:

./main
11

最简单的例子;请注意,由于Base不是纯虚拟的,所以它很复杂。我们开始了:

  1. baz.cpp公司:

    #include<string>
    #include<boost/python.hpp>
    using std::string;
    namespace py=boost::python;
    
    struct Base{
      virtual string foo() const { return "Base.foo"; }
      // fooBase is non-virtual, calling it from anywhere (c++ or python)
      // will go through c++ dispatch
      string fooBase() const { return foo(); }
    };
    struct BaseWrapper: Base, py::wrapper<Base>{
      string foo() const{
        // if Base were abstract (non-instantiable in python), then
        // there would be only this->get_override("foo")() here
        //
        // if called on a class which overrides foo in python
        if(this->get_override("foo")) return this->get_override("foo")();
        // no override in python; happens if Base(Wrapper) is instantiated directly
        else return Base::foo();
      }
    };
    
    BOOST_PYTHON_MODULE(baz){
      py::class_<BaseWrapper,boost::noncopyable>("Base")
        .def("foo",&Base::foo)
        .def("fooBase",&Base::fooBase)
      ;
    }
    
  2. 酒吧.py

    import sys
    sys.path.append('.')
    import baz
    
    class PyDerived(baz.Base):
      def foo(self): return 'PyDerived.foo'
    
    base=baz.Base()
    der=PyDerived()
    print base.foo(), base.fooBase()
    print der.foo(), der.fooBase()
    
  3. 生成文件

    default:
           g++ -shared -fPIC -o baz.so baz.cpp -lboost_python `pkg-config python --cflags`
    

结果是:

Base.foo Base.foo
PyDerived.foo PyDerived.foo

在这里您可以看到fooBase()(非虚拟c++函数)如何调用virtualfoo(),无论是在c++还是python中,virtualfoo()都解析为重写。你可以在c++中从基类派生一个类,它的工作原理是一样的。

编辑(提取c++对象):

PyObject* obj; // given
py::object pyObj(obj); // wrap as boost::python object (cheap)
py::extract<Base> ex(pyObj); 
if(ex.check()){ // types are compatible
  Base& b=ex(); // get the wrapped object
  // ...
} else {
  // error
}

// shorter, thrwos when conversion not possible
Base &b=py::extract<Base>(py::object(obj))();

PyObject*构造py::object,并使用py::extract查询python对象是否与您试图提取的内容匹配:PyObject* obj; py::extract<Base> extractor(py::object(obj)); if(!extractor.check()) /* error */; Base& b=extractor();

引用http://wiki.python.org/moin/boost.python/Inheritance

< P>。Pyth.Python还允许我们表示C++继承关系,从而可以将包装的派生类传递到其中,将值、指针或引用作为基类的参数作为参数。

有一些虚拟函数的例子,这样就解决了第一部分(带有MyCl(myif)类的函数)

对于执行此操作的特定示例,http://wiki.python.org/moin/boost.python/OverridableVirtualFunctions

> MyIF C= MyCL();您需要将Python(模块)暴露给C++。这里有一些例子http://wiki.python.org/moin/boost.python/EmbeddingPython

相关问题 更多 >