Friday, June 2, 2017

Interaction of C++ and Python via Boost.Python

  • Download latest boost package from http://www.boost.org/.
  • Unzip and go inside the folder: cd ~/Downloads/boost_1_62_0
  • Run ./bootstrap.sh
  • Then run ./b2 . This will build all the shared libraries in ~/Downloads/boost_1_62_0/stage/lib.(we are interested in boost_python library as of now)
  • Copy headers and libraries to standard path:
    • sudo cp -r ~/Downloads/boost_1_62_0/boost /usr/local/include/
    • sudo cp ~/Downloads/boost_1_62_0/stage/lib/libboost_python.* /usr/local/lib/
  • Append Python wrapper code in C++ so that existing C++ code is not changed at all. [ Caution: Nomenclature of file name and module should be same!!! ]
        char const* greet()
        {
             return "hello, world";
        }
 
        #include <boost/python.hpp>
 
        BOOST_PYTHON_MODULE(<module>)
        {
             using namespace boost::python;
             def("greet", greet);
        }
  • g++ -c <filename>.cpp -o <filename>.o -fPIC && g++ -c <other_filename>.cpp -o <other_filename>.o
  • For following error "/usr/local/include/boost/python/detail/wrap_python.hpp:50:11: fatal error: 'pyconfig.h' file not found", add -I/usr/include/python2.7/ while compiling.
  • g++ -shared <filename>.o <other_filename>.o -lboost_python -lpython2.7 -o <filename>.so ( If <filename>.cpp depends on <other_filename>.cpp, put its compiled object as well. Include -litpp if the c++ code depends on IT++ library)
  • Put the shared library in the standard python module path: cp <filename>.so /Library/Python/2.7/site-packages/
  • Open .py file and call the C++ function: [ module and C++ filename are same ]
        import <module>
        module.greet();
  • For passing an argument from Python to C++, simply do the following:

     In C++:

     char const* greet(string name)
     {
        if(name != null) {
            return "hello " + name;
        } else {
            return "hello, world";
        }
     }
 
     #include <boost/python.hpp>
 
     BOOST_PYTHON_MODULE(<module>)
     {
         using namespace boost::python;
         def("greet", greet);
     }

    In Python:

    import <module>
    module.greet("Rajanya");

2 comments:

  1. coding classes for kids online Very efficiently written information. It will be beneficial to anybody who utilizes it, including me. Keep up the good work. For sure i will check out more posts. This site seems to get a good amount of visitors.

    ReplyDelete