current position:Home>Boost(2):boost. Python library introduction and simple examples
Boost(2):boost. Python library introduction and simple examples
2022-05-15 06:01:28【Xiangdi】
1. boost.python Introduce
take c/c++ The function interface of is converted to Python There are several solutions for interfaces , differ C The simplicity and directness of language ,C++ Due to the use of a large number of object-oriented programming ideas, it is converted to Python The interface is relatively complex ,boost.python Our goal is to make it easy to C++ Program into Python The interface of .
BoostPython Kuo is boost c++ One of the sub libraries of the library , Using it, you can easily C++ The function interface of is converted into Python Interface . In most cases, you don't have to deal with the original C++ Make any changes to the code ,boost.python Would be right C++ Class to do another layer of encapsulation , Make it compile to conform to Python The language standard of .
2. Simple routines
According to the programmer's Jianghu rules , A new learning begins , First of all, from the HelloWorld Start with the program . In this routine , use first c++ Output function "hello world", Then encapsulate this function into python The interface of , stay python Call this function to print in the environment .
notes : This routine runs in boost_1_73_0 Under the version .
The overall document structure is as follows :
/boost$ tree
├── 01_HelloWorld
│ ├── CMakeLists.txt
│ ├── hello.py
│ └── HelloWorld.cpp
└── CMakeLists.txt
1 directory, 4 files
establish boost Example directories for saving subsequent code ,boost In the catalog CMakeLists.txt It mainly completes the search of necessary Libraries , For example, it will be used here Python and Boost, Then add... Under the subdirectory CMakeLists.txt file .
2.1 Home directory CMakeLists.txt
The contents are as follows :
project(Boost_Test)
cmake_minimum_required(VERSION 2.8.3)
# find python
find_package(PythonInterp REQUIRED)
find_package(PythonLibs ${
PYTHON_VERSION_MAJOR}.${
PYTHON_VERSION_MINOR} EXACT REQUIRED)
# now search for the boost component
# depending on the boost version it is called either python,
# python2, python27, python3, python36, python37, ...
list(
APPEND _components
python${
PYTHON_VERSION_MAJOR}${
PYTHON_VERSION_MINOR}
python${
PYTHON_VERSION_MAJOR}
python
)
message(BOOST_ROOT " ${BOOST_ROOT}")
set(_boost_python_found "")
set(Boost_NAMESPACE "libboost")
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_LIBS OFF)
set(Boost_USE_STATIC_RUNTIME OFF)
foreach(_component IN ITEMS ${
_components})
find_package(Boost COMPONENTS ${
_component})
if(Boost_FOUND)
set(_boost_python_found ${
_component})
break()
endif()
endforeach()
#if(_boost_python_found STREQUAL "")
# message(FATAL_ERROR "No matching Boost.Python component found")
#endif()
include_directories("${PYTHON_INCLUDE_DIRS}")
include_directories("${Boost_INCLUDE_DIRS}")
message(PYTHON_INCLUDE_DIRS " ${PYTHON_INCLUDE_DIRS}")
message(PYTHON_LIBRARIES " ${PYTHON_LIBRARIES}")
message(Boost_INCLUDE_DIRS " ${Boost_INCLUDE_DIRS}")
message(Boost_LIBRARIES " ${Boost_LIBRARIES}")
ADD_SUBDIRECTORY(01_HelloWorld)
2.2 HelloWorld.cpp
char const* greet()
{
return "hello, world";
}
#include <boost/python.hpp>
BOOST_PYTHON_MODULE(hello)
{
using namespace boost::python;
def("greet", greet);
}
2.3 hello.py
#!/usr/bin/env python
import hello
print (hello.greet())
2.4 Under subdirectories CMakeLists.txt
This file mainly completes the compilation of library files and links , Be careful MODULE_NAME Must be with BOOST_PYTHON_MODULE() It's the same under , For example, here are hello.
set(MODULE_NAME hello)
include_directories(${
CMAKE_SOURCE_DIR})
add_library(${
MODULE_NAME} SHARED
HelloWorld.cpp
)
if (UNIX)
set_target_properties(${
MODULE_NAME}
PROPERTIES
PREFIX ""
)
elseif (WIN32)
set_target_properties(${
MODULE_NAME}
PROPERTIES
SUFFIX ".pyd"
)
endif()
target_link_libraries(${
MODULE_NAME}
${
Boost_LIBRARIES}
${
PYTHON_LIBRARIES}
)
about windows System , Compilation of python Modules should be ".pyd" For the suffix . And for linux System , By default, the module name will be preceded by "lib", and Boost.Python The module name and library file name are required to be consistent , So here we want to declare that we don't prefix the library file .
3. Compile operation
3.1 compile
cd boost
mkdir build
cmake ..
make
after , stay build/01_HelloWorld The directory will generate hello.so Library file .
3.2 function
cd 01_HelloWorld
# Are you there? install so Under the circumstances , take python File copy to so Catalog
cp ../../01_HelloWorld/hello.py .
python hello.py
3.3 Running results
#python hello.py
hello, world
4. Boost Interface
4.1 BOOST_PYTHON_MODULE macro
In this macro definition boost/python/module.hpp Under the document , This file provides a way to create Boost.Python Basic tools for extension modules . At present, there is only this macro .
BOOST_PYTHON_MODULE For declaration python Module initialization function , Its use format is as follows :
BOOST_PYTHON_MODULE(name)
{
...
}
name The parameter must exactly match the name of the module to be initialized , And must comply with Python Identifier naming rules for .
4.2 def
def Interface is Boost.Python Free function version provided , It can convert the function in the current scope into python The interface of , As in the example greet() function . You will also see the version of the function in the conversion class later .
def Is used as follows :
#include <boost/python.hpp>
BOOST_PYTHON_MODULE(my_module)
{
def("name", function_ptr);
def("name", function_ptr, call_policies);
def("name", function_ptr, "documentation string");
def("name", function_ptr, call_policies, "documentation string");
}
among name Express python Function name under interface , It can be done with c++ The names are different .function_ptr Is the corresponding c++ A function pointer , That is, the function name .call_policies I'll explain it in detail when I use it later .
Reference material
https://wiki.python.org/moin/boost.python/GettingStarted
https://www.boost.org/doc/libs/1_78_0/libs/python/doc/html/tutorial/index.html
copyright notice
author[Xiangdi],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/131/202205110608082338.html
The sidebar is recommended
- Python development alert notification SMS alert
- How to configure Python environment library offline in FME
- Python: fastapi - beginner interface development
- Generate password based on fast token and fast token
- [Django CI system] use of json-20220509
- [Django CI system] if the front-end date is complete, it will be fully updated to the back-end; If the front-end date is incomplete, the date will not be updated to the back-end-20220510
- [Django CI system] echarts dataset standard writing - 20220509
- [Django CI system] obtain the current time, the first day and the last day of the month, etc. - 20220510
- wxPython wx. Correction of font class · Wx Font tutorial
- NCT youth programming proficiency level test python programming level 3 - simulation volume 2 (with answers)
guess what you like
Design of personal simple blog system based on Django (with source code acquisition method)
[Python Script] classify pictures according to their definition
Wu Enda's classic ml class is fully upgraded! Update to Python implementation and add more intuitive visual teaching
Six built-in functions called immortals in Python
Some insights of pandas in machine learning
Introduction to Python [preliminary knowledge] - programming idea
Stay up late to tidy up! Pandas text processing Encyclopedia
Python recursion to find values by dichotomy
Open 3D Python Interface
[true title 02 of Blue Bridge Cup] Python output natural number youth group analysis of true title of Blue Bridge Cup Python national competition
Random recommended
- Introduction to the differences between Python and Java
- Explain Python CONDA in detail
- The pycham downloaded by MAC reports an error as soon as it is opened. The downloaded Python interpreter is also the latest version
- From entry to mastery, python full stack engineers have personally taught Python core technology and practical combat for ten years
- Python is used to detect some problems of word frequency in English text.
- How to choose between excel, database and pandas (Python third-party library)?
- WxPython download has been reporting errors
- Pyside6 UIC and other tools cannot be found in the higher version of pyside6 (QT for Python 6). How to solve it?
- About Python Crawlers
- Successfully imported pandas, unable to use dataframe
- How to extract some keywords in the path with Python
- Python encountered a problem reading the file!
- When Python is packaged into exe, an error is reported when opening assertionerror: C: \ users \ Acer \ appdata \ local \ temp\_ MEI105682\distutils\core. pyc
- Eight practical "no code" features of Python
- Python meets SQL, so a useful Python third-party library appears
- 100 Python algorithm super detailed explanation: a hundred dollars and a hundred chickens
- [fundamentals of Python] Python code and so on
- When Python uses probit regression, the program statement is deleted by mistake, and then it appears_ raise_ linalgerror_ Unrecognized error of singular
- Python testing Nicholas theorem
- Accelerating parallel computing based on python (BL) 136
- Python dynamic programming (knapsack problem and longest common substring)
- Django uses queryset filter save, and an 'queryset' object has no attribute 'Save' error occurs. Solution?
- Analysis of built-in functions in Python learning
- Python office automation - 90 - file automation management - cleaning up duplicate files and batch modifying file names
- Python office automation - 91 - word file Automation - word operation and reading word files
- After python, go also runs smoothly on the browser
- Self taught Python 26 method
- Summary of Python Tkinter component function examples (code + effect picture) (RadioButton | button | entry | menu | text)
- Python implementation of official selection sorting of Luogu question list
- Application of Django template
- Get project root path and other paths in Python project
- Get, rename, and delete file names in Python projects
- How to set the width and height of Python operation table
- Python string preceded by 'f' R 'B' U '
- JSON and other types convert to each other in Python
- Key value of key combination in pynput in Python
- Conversion of Python PDF file to word file
- Interface testing uses Python decorators
- Get the current time in Python
- Python course notes -- Python string, detailed explanation of related functions