Getting started with boost. Python -- embedding python in C ++

Source: Internet
Author: User

In boost. Python, python is embedded in the C ++ section, and Chinese documents found on the Internet seem to be outdated,

Such as boost. Python Study Notes http://edyfox.codecarver.org/html/boost_python.html

InBoost. Python version 2To provide more concise and easy-to-use interfaces.

Replace the originalPython c Conversion API, such as pyrun_simplestring.

 

There are actually two parts about Python and C ++ mixed programming.

    1. ExtendingPythonProgramC/C ++CodeIn fact, it is to first process the C ++ code and a pre-generated dynamic link library, such as example. So, and import example; in Python code, you can use C/C ++ functions.
    2. EmbeddingC ++ code calls the Python code.

You can use the python c Conversion API to solve both of them. For details, refer to the official Python documentation, but they are complicated.

For 1,ExtendingThe common solution isBoost. PythonAndSwig.

Swig is a glue language that binds C ++ and python. The preceding figure shows the binary tree.ArticleUsing pyqt as the interface,

Call the C ++ code and use the. So dynamic library generated by swig.

While boost. python is directly converted and can be usedPY ++Automatically generate the required wrapper. In addition to boost. Python

Official website, Chinese entry material recommendations

 

Build a cross-language GUI program using boost. Python + cmake + wxpython <1>

 

Http://www.cppblog.com/skyscribe/archive/2009/08/09/92686.html

There are three series in total. His blog also contains cmake content. The environment in this article will also be compiled using cmake for your reference.

For 2It seems that swig does not provide support. swig not only supports python to call C/C ++, but also supports many other advanced languages to call C ++. However, swig does not support python to embed C ++.

Next we will only introduce2 embeddingIn fact, embedding is much simpler than extending :)

This section describes the specific instance code and environment configuration methods. Some of them are for simplicity and are not the best configuration scheme,

For example, use cmake.

    • Environment Configuration

My work environment is ubuntu8.04, gcc4.24, cmake2.6, boost1.4, python2.6.

If you work in Windows, you don't have to look down.

Boost. Python does not seem to support python3, so I personally recommend using python2.6. Of course, the built-in python2.5 of ubuntu8.04

Yes.

1. Installation of python2.6

Download python2.6 from the official website and decompress it,

./Configure -- enable-shared; Make; sudo make install

The header file should be installed in/usr/local/include/python2.6by default.

Note that the first step./configure -- help can be used to view the help options. If you want to set the installation path,

Special note-- Enable-sharedOption to generate a dynamic link library, libpython2.6.so

This is what we need below. We must have this option! By default, it is generated under/usr/local/lib.

The dynamic link library is not generated.

2. Install cmake

Sudo apt-Get Insall cmake. You can also download and install the latest cmake2.8 on the official website.

3. Boost Installation

Download boost.1.4.2 from the official website and decompress it.

./Bootstrap. Sh -- Help

./Bootstrap. Sh -- show-libraries # It will show you which libraries can be installed

Here, we will explain that boost is a template library, many of which only need header files and do not need to be compiled and installed. However, some libraries need to be installed, as shown in figure

RegEx, Python, etc. You can check and select the library you want to install.

I have selected all installation. By default, all installation is performed.

./Bootstrap. Sh -- prefix =/usr/local/boost1.4

This will install the header file to/usr/local/boost1.4/include

Install the library file to/usr/local/boost1.4/lib

Then

./BjamInstall

Note that the file will not be copied to the specified installation path without installing.

Then you can set the environment variables, such as boost_root and boost_lib.

The following installation path is directly written during my experiment, such as/usr/local/boost1.4/include

    • How to Implement the conversion API directly using Python and C.

Let's look at the simplest example.

# Include < Python. h >
Int
Main ( Int Argc, Char   * Argv [])
{
Py_initialize ();
Pyrun_simplestring ( " From time import time, ctime \ n "
" Print 'Today is ', ctime (Time () \ n " );
Py_finalize ();
Return   0 ;
}

Assume that this program is named A. CC. How can we compile it? You must find the python header file and dynamic link library as follows:

G ++-I/usr/local/include/python2.6-lpython2.6-O A. cpp

./

Today is Sun Nov 15 17:25:25 2009

    • Support for boost. Python

To use boost. Python, follow these steps:

 

    1. # Include<Boost/python. HPP>
    2. Call py_initialize () to enable the interpreter and generate_ Main_Module.
    3. Use this interpreter to call Python c api. note that you must not call py_finalize to end the interpreter. This issue may be removed in later versions. of course, you can have other C ++ code in these steps.

Let's look at the Code directly. Boost. Python provides three methods to call Python code,

Eval, exec, exec_file,

Corresponding

Calculate the expression value,

Execute the python statement,

Execute Python text such as A. py.

The use of Boost: Python: object makes it easy to call functions in Python.

The following code demonstrates the use of exec, exec_file, and object, basically covering all common requirements.

First, write a simple Python file,

Simple. py

Def Foo (I =   4 ):
Return I +   2008

 

Write a C ++ code

Embedding. CC

 

# Include < Iostream >
Using   Namespace STD;
# Include < Boost / Python. HPP >
Using   Namespace Boost: Python;

IntMain (IntArgc,Char *Argv [])
{
Py_initialize ();

Object Main_module = Import ( " _ Main __ " );
Object Main_namespace = Main_module.attr ( " _ Dict __ " );
Exec ( " Hello = file('hello.txt ', 'w') \ n "
" Hello. Write ('Hello world! ') \ N "
" Hello. Close () " ,
Main_namespace );
Exec ( " Result = 5 ** 2 " , Main_namespace );
Int Five_squared = Extract < Int > (Main_namespace [ " Result " ]);
Cout <   " The five_squeared caculated by python is "   < Five_squared < Endl;

//Load the SYS module.
ObjectSys=Import ("Sys");

// Extract the Python version.
STD :: String Version = Extract < STD :: String > (SYS. ATTR ( " Version " ));
STD: cout < Version < STD: Endl;


// Simple. py must be in the same path as the executable file! Run OK
Object Simple = Exec_file ( " Simple. py " , Main_namespace, main_namespace );
// Dict global;
// Object result = exec_file ("Simple. py", global, global );
Object Foo = Main_namespace [ " Foo " ];
Int Val = Extract < Int > (FOO ( 5 ));
Cout <   " Python has caculated Foo "   < Val < Endl;

Return 0;
}

How to compile this program is actually the python that can be found, as well as the header file and library file of boost. Python. I used cmake to manage it.

Create a cmakelists.txt file under the same code folder and write the following content. Note that you may need to install the file according to your own installation path.

Change.

Project (embedding) # create a project name

# boost. python and Python header file path
include_directories (/ USR / Local / boost1. 4 / include / USR / Local / include / python2. 6 )

Link_directories (/USR/Local/Boost1.4/Lib/USR/Local/Lib) # boost. Python, Python dynamic link library path

Add_executable (embedding. CC) # generate the executable file embedding in the source file embedding. CC.
Target_link_libraries (embedding libboost_python.so libpython2.6. So) # The executable file dependency and the two libraries

 

If you have configured environment variables, the default location of the header file library, or the application ln may not need to be so cumbersome, This is a feasible solution.

Cmake.

Make

./Embedding

The five_squeared caculated by python is 25
2.6.2 (r262: 71600, Nov 14 2009, 14:18:33)
[GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu4)]
Python has caculated fooas 2013

 

 

 

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.