Boost.python Getting Started tutorial----python embedded in C + +

Source: Internet
Author: User

Boost.python python embedded in the C + + section, the Chinese information found online seems to be a bit outdated,

such as Boost.python study notes http://edyfox.codecarver.org/html/boost_python.html

In Boost.python version 2, we provide a more concise and easy-to-use interface

Instead of the original pyrun_simplestring and so on Python C conversion API.

About Python and C + + mixed programming, in fact there are two parts

    1. extending called C + + code in a Python program, in fact, the first process of C + + code, pre-generated dynamic link libraries, such as example.so, and in Python code import example; The function.
    2. The Python code is called in embedding C + + code.

Both can be used in Python C conversion API, the specific can go to the official Python document lookup, but are more cumbersome.

For 1,extending, the common scenario is boost.python and swig.

Swig is a kind of glue language, glue C++,python, I front of the graphic display binary tree article mentioned is the use of PYQT as interface,

Call C + + code to use the. So dynamic library generated by Swig.

The Boost.python is converted directly, you can use py++ to generate the required wrapper automatically. Getting Started with content in this area in addition to Boost.python

Official website, Chinese introductory Materials recommended

Build a cross-language GUI program with Boost.python + CMake + Wxpython < a >

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

Altogether 3 Series, his blog also has the CMake content, this article's environment also will use the CMake compiles, may provide the reference.

For 2 It seems Swig does not support it, swig not only supports Python calls C + +, but also supports many other high-level languages calling C + +, but it does not support Python embedding C + +.

The following is just about 2 embedding, in fact embedding is much simpler than extending:)

This will give the specific instance code and the environment configuration method. Some are just for simplicity, not the best configuration scenario,

such as the use of cmake.

    • Environment configuration

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

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

Boost.python does not seem to support Python3 so personally recommend the use of python2.6, of course ubuntu8.04 comes with python2.5

It's possible.

Installation of 1.python2.6

Go to the official website to download python2.6, unzip,

./configure--enable-shared;make; sudo make install

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

Note the first step./configure--help can view help options, such as what path you want to set to install to,

Pay special attention to the--enable-shared option to generate a dynamic-link library, libpython2.6.so

This is what we need below must have this option! The default will be generated to/usr/local/lib, you directly./configure

, a dynamic-link library is not generated.

2. CMake Installation

sudo apt-get insall cmake can also go to the official website to download and install the latest cmake2.8

3. Boost installation

Go to official website download boost.1.4.2 unzip

./bootstrap.sh--help

./bootstrap.sh--show-libraries #会显示你有哪些库可以安装

Explain here, because boost is a template library, many of them only need header files, do not need to compile the installation, but some libraries need to be installed such as

Regex,python, wait, you can check out the libraries you need to install yourself.

I have chosen to install all, by default it is all installed.

./bootstrap.sh--prefix=/usr/local/boost1.4

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

Library files installed to/usr/local/boost1.4/lib

And then

./bjam Install

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

Then you can set the environment variables, such as Boost_root,boost_lib

Following my experiment, I wrote the installation path directly, such as/usr/local/boost1.4/include

    • How to do this directly with the Python,c conversion API.

Look at one of the simplest examples

#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;
}

Suppose this program is named a.cc, how to compile it. There is no need to find Python header files and dynamic link libraries. The following:

g++-i/usr/local/include/python2.6-lpython2.6-o a A.cpp

./A

Today is Sun Nov 15 17:25:25 2009

    • Boost.python's support

The following steps are required to use Boost.python

    1. #include <boost/python.hpp>
    2. Call Py_initialize () to turn on the interpreter and generate the _main_ module.
    3. Use this interpreter to invoke the Python C API. Note that you must not finally call Py_finalize to end the interpreter, this problem may be changed in later versions. Of course you can have other C + + code in these steps.
Or just look at the code, Boost.python provides 3 ways to call Python code,

eval, exec, Exec_file,

respectively corresponding

Evaluates an expression value,

Executes the Python statement,

Executes python text such as a.py.

and boost: The use of:p Ython::object makes it simple to invoke the function exception in Python.

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

Start by writing 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::p Ython;

int main (int argc, 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" << five_squared << Endl;

Load the SYS module.
Object sys = import ("sys");

Extract the Python version.
std::string Version = extract<std::string> (sys.attr ("version"));
Std::cout << version << Std::endl;


Requires simple.py to be under 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 as" << Val << Endl;


return 0;
}

How to compile this program, is actually can find Python, as well as Boost.python's header files and library files. I used CMake, management.

The simplest is to create a file CMakeLists.txt under the same code path, write the following, and note that you may need to follow your own installation path

Change.

Project (embedding) #随便起一个工程名称

#boost. Python,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 embedding.cc) #源文件embedding. CC to generate the executable file embedding
Target_link_libraries (embedding libboost_python.so libpython2.6.so) #可执行文件依赖与这两个库

This is a viable scenario if you configure environment variables, or if the header vault is in the default find location, or if you apply ln may not be so cumbersome.

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 foo as 2013

Boost.python Getting Started tutorial----python embedded in C + +

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.