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:28Xiangdi

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

https://www.boost.org/doc/libs/1_78_0/libs/python/doc/html/reference/high_level_components/boost_python_module_hpp.html

copyright notice
author[Xiangdi],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/131/202205110608082338.html

Random recommended