Can a python-C ++ extension get a C ++ object and call its member function?

I am writing a python / C ++ application that will call methods in a C ++ extension from python.

Say my C ++ has a class:

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

A a=A();

In any case, python can get the object ain C ++ and call its member function, i.e.:

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

Any reference to general reading is also welcome.

+4
source share
2 answers

Yes. You can create a Python C ++ extension where your C ++ objects will be visible inside Python as if they were built-in types.

There are two main ways to do this.

1.Create an extension yourself, following the documentation provided in the CPython API Documentation .

2. , boost:: python SWIG.

boost:: python - ( , , , , ).

boost:: python :

// 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

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})
+4

: , . , , ++ Python.

:

, ++ class_file.h. .pxd

cdef extern from "class_file.h":
    cdef cppclass A:
        int _i
        A(int)
        int get_i

++. , , Cython. .pyx cimport pxd , . setup.py, .so, Python , python.

http://docs.cython.org/src/tutorial/cython_tutorial.html . , Cython .

+2

All Articles