我正在编写一个 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/