【问题标题】:C++ and Python tight integratingC++ 和 Python 紧密集成
【发布时间】:2017-04-05 20:59:14
【问题描述】:

我有 C++ 程序,我想用 Python 添加扩展系统。但要实现这一点,我必须将 Python 对象方法调用映射到 C++ 方法调用。这可能吗?如果可以,如何实现。

示例
Python部分:

class Extension(AbstractExtension):
    def __init__(self, cool_cpp_object):
        self.o = cool_cpp_object

    def some_method(self):
        self.o.method_to_cpp()

C++部分:

class SomeClass : public AnotherClass
{
public:
    void method_to_cpp();
}

我必须将 SomeClass 实例传递给 Extension 实例方法。谢谢。

【问题讨论】:

标签: python c++ integration


【解决方案1】:

有几种方法可以做到这一点(StoryTeller 正确地记下了 Boost::Python,还有Swig)。就个人而言,我发现Cython's C++ integration 非常易于使用。

创建一些头文件,比如classes.hpp,并在其中放入(连同守卫等):

class SomeClass : public AnotherClass
{
public:
    void method_to_cpp();
}

以通常的方式将实现放在实现文件中。

现在创建 Cython 文件,导出您将使用的界面:

cdef extern from "classes.hpp":
cdef cppclass SomeClass:
    method_to_cpp()

和一个 Python 包装器:

cdef class PySomeClass:
     cdef SomeClass obj

     def method(self):
         self.obj.method_to_cpp()

基本上就是这样。你可以像普通的 Python 类一样导入和使用PySomeClass

上面的链接应该解释了如何构建所有文件。

【讨论】:

  • 好的,我浏览了链接,将 C++ 集成到 python 非常容易,但我仍然不知道如何将已经创建的 C++ 对象传递给 Python。
  • @Megaxela 它是PySomeClass 的(Cython)成员,您可以像普通的 Python 对象一样传递它。其他Python代码可以调用PySomeClass的成员,其成员可以调用C++对象的方法。
猜你喜欢
  • 2010-11-12
  • 2014-02-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-22
  • 1970-01-01
  • 1970-01-01
  • 2019-07-10
  • 2021-02-17
相关资源
最近更新 更多