Writing extended Python modules with C + + boost

Source: Internet
Author: User

Python is powerful, but existing modules may not meet the people's growing material and cultural needs, and sometimes need to write extension modules to improve.


There are a number of possible options: SWIG, Weave, cTYPES, BOOST ...


Boost is undoubtedly one of the fastest development scenarios. The following describes how the simplest C + + HelloWorld program becomes a python module.


1. Install Python, Boost

Here with the Linux environment. Both Python and boost are installed in source code, with the following URLs:

python2.6:https://www.python.org

Boost1.57.0:http://sourceforge.net/projects/boost/?source=typ_redirect


2. Writing Helloworld.cpp

#define Boost_python_source#include <boost/python.hpp> #include <iostream>using namespace std;using Namespace boost::p ython;void hello_func () {        cout<< "Hello boost Python" <<ENDL;} Boost_python_module (boostpy) {        def ("Hello", Hello_func, "Function ' s targets ...");}

3. Compiling as a dynamic library

Command line execution:

g++-shared-o Boostpy.so-fpic-i/yourpythonincludepath/helloworld.cpp-lpython2.6-lboost_python

Generated a dynamic link library boostpy.so


4. Calling hello in the python environment

>>> Import boostpy>>> boostpy.     Hello () Hello boost python>>>help (boostpy) Help on module Boostpy:name boostpyfile/...../boostpy.sofunctions        Hello (...)            Hello ()-none:function ' s targets ... C + + signature:void Hello () (END)

Summary: Here is only the simplest call, without the problem of parameter passing. You'll continue to look at how to share data between C + + and Python later.

Writing extended Python modules with C + + boost

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.