Yes. You can create a Python C++ extension where your C++ objects will be visible from within Python as if they were built-in types.
There are two main ways to go about it.
1.Create the extension yourself following the documentation provided in the CPython API Documentation.
2.Create the extension using a tool such as boost::python or SWIG.
In my experience boost::python is the best way to go about it (it saves you an enormous amount of time, and the price you pay is that now you depend on boost).
For your example, the boost::python bindings could look as follows:
// 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")
;
}
Compile:
g++ -o foo.so foo.cpp -std=c++11 -fPIC -shared \
-Wall -Wextra `python2.7-config --includes --libs` \
-lboost_python
and run in 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})