python - python-C++扩展能否获取C++对象并调用其成员函数?

标签 python c++ python-extensions

我正在编写一个 python/C++ 应用程序,它将从 python 调用 C++ 扩展中的方法。

假设我的 C++ 有一个类:

class A
{
    private:
        int _i;
    public:
        A(int i){_i=i;}
        int get_i(){return _i;}
}

A a=A();

无论如何,python 可以在 C++ 中获取 a 对象并调用其成员函数,即:

import cpp_extension
a=cpp_extension.A()
print a.get_i()

也欢迎任何对一般阅读的引用。

最佳答案

是的。您可以创建一个 Python C++ 扩展,您的 C++ 对象将在 Python 中可见,就像它们是内置类型一样。

主要有两种方法。

1.按照 CPython API Documentation 中提供的文档自行创建扩展。 .

2.使用 boost::python 等工具创建扩展或 SWIG .

根据我的经验,boost::python 是最好的方法(它为您节省了大量时间,而您付出的代价是现在您依赖于 boost)。

对于您的示例,boost::python 绑定(bind)可能如下所示:

// foo.cpp
#include <boost/python.hpp>

class A {

 public:

  A(int i)
      : m_i{i} { }

  int get_i() const {
    return m_i;
  }
 private:
  // don't use names such as `_i`; those are reserved for the
  // implementation
  int m_i;
};

BOOST_PYTHON_MODULE(foo) {
  using namespace boost::python;

  class_<A>("A", init<int>())
      .def("get_i", &A::get_i, "This is the docstring for A::get_i")
      ;
}

编译:

g++ -o foo.so foo.cpp -std=c++11 -fPIC -shared \
-Wall -Wextra `python2.7-config --includes --libs` \
-lboost_python

并在 Python 中运行:

>>> import foo
>>> a = foo.A(2)
>>> a.get_i()
2
>>> print a.get_i.__doc__

get_i( (A)arg1) -> int :
    This is the docstring for A::get_i

    C++ signature :
        int get_i(A {lvalue})

关于python - python-C++扩展能否获取C++对象并调用其成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31391400/

相关文章:

python - 尝试从 CloudWatch 获取最新的 LogStream 时出现奇怪的行为

python - 如何使用python在打印语句的for循环中插入换行符

c++ - %*c 是什么意思?

c - 从 C 定义 Python 类

Python 函数胶囊

python - 使用不同的 Visual Studio 版本编译 Python 扩展

python - Keras 有没有办法立即停止训练?

c++ - C++模板模棱两可的实例化

c++ - 运行时错误,可能是输入问题?

python - 机器学习: Classification on imbalanced data