小编hal*_*al3的帖子

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

我有一个用C++编写的类接口.我有一些实现此接口的类也是用C++编写的.这些是在更大的C++程序的上下文中调用的,它基本上实现了"main".我希望能够在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);
};
Run Code Online (Sandbox Code Playgroud)

我想要做的是:

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

然后,回到我的C++代码中,我希望能够说出类似的话:

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

我希望这很清楚;)

c++ python swig boost-python

37
推荐指数
4
解决办法
9001
查看次数

标签 统计

boost-python ×1

c++ ×1

python ×1

swig ×1