Use pybind11 to encapsulate the function implementation steps of C + + structure as parameters

Time:2021-10-24

There are many methods for Python to call C / C + +, such as boost.python, swig, ctypes, pybind11, etc. these methods are complex and simple. The advantage of pybind11 is that it supports C + + 11 very well and the API is relatively simple. Now let’s simply write down the introduction operation of pybind11.

Introduction to pybind11

Pybind11 is a lightweight library containing only header files. It is mainly used to extend the existing C + + code. Its syntax and goal are very similar to boost.python, but boost.python becomes very complex and huge in order to be compatible with almost all existing C + + compilers, The cost is a lot of obscure template skills and a lot of unnecessary support for older compilers. Pybind11 discards these supports. It only supports compilers above Python 2.7 and C + + 11, making it more concise and efficient than boost. Python.

In C language, struct refers to a data structure, which is a kind of aggregate data type in C language. Structures can be declared as variables, pointers or arrays to implement more complex data structures. A structure is also a collection of elements. These elements are called members of the structure, and these members can be of different types. Members are generally accessed by name.

Structures and structure pointers are widely used as parameters of functions. This paper introduces how to use pybind11 to encapsulate functions with C + + structures as parameters.

1、 Demand analysis

  • The existing structure named student has five member variables name, Chinese, mathematics, English and total. The constructor generates an instance through name, and the member function setname can assign a value to the name of the instance;
  • The calc function receives a student instance as a parameter and calculates the total score from the scores of the three courses;
  • Encapsulate student and calc into a python module (abctest) containing a student class and a Calc function.

2、 Implementation steps

  1. Define the student structure in the header file and declare the calc function;
  2. Implement func.cpp function in C + + source file;
  3. Write pybind11 encapsulation function;
  4. Write setup script in Python;
  5. Compile and generate dynamic link library;
  6. Test function function.

3、 Code implementation

Define the student structure in the header file and declare the calc function

//File name: whjy. H
#include <string> 
using namespace std; 
struct student{ 
 string name; 
 int Chinese; 
 int Mathematics; 
 int English; 
 int total; 
 student(string n){ 
 this->name = n; 
 } 
 void setName(string stuName){ 
  this->name = stuName; 
 } 
}; 
void calc(struct student&);

Implement func.cpp function in C + + source file

//File name: func.cpp
#include "whjy.h" 
#include <string> 
void calc(struct student& tyh){ 
 tyh.total = tyh.Chinese + tyh.Mathematics + tyh.English; 
}

Write pybind11 encapsulation function

//File name: func_ wrapper.cpp
#include <pybind11/pybind11.h> 
#include "whjy.h" 
namespace py = pybind11; 
PYBIND11_MODULE(abctest, m){ 
 m.doc() = "simple example"; 
 
 py::class_<student>(m, "student") 
  .def(py::init<string>()) 
  .def("setName", &student::setName) 
  .def_readonly("name", &student::name) 
  .def_readwrite("Chinese", &student::Chinese) 
  .def_readwrite("Mathematics", &student::Mathematics) 
  .def_readwrite("English", &student::English) 
  .def_readwrite("total", &student::total); 
 m.def("calc", &calc); 
}

Writing setup script in Python

#File name: setup.py
from setuptools import setup, Extension 
 
functions_module = Extension( 
 name = 'abctest', 
 sources = ['func.cpp', 'func_wrapper.cpp'], 
 include_dirs = [r'D:\software\pybind11-master\include', 
     r'D:\software\Anaconda\include'] 
) 
 
setup(ext_modules = [functions_module])

Compile and generate dynamic link library

Execute on the command linepython setup.py build_ext --inplace , generate PYD dynamic library under the current path.

Test function function

#File name: test.py
import abctest 
S = abctest.student ("Xiao Ming") 
s.Chinese = 100 
s.Mathematics = 110 
s.English =120 
abctest.calc(s) 
Print (s.name + ":" + str (s.total) + "Min") 
print("----------------------") 
s. Setname ("little red") 
Print (s.name + ":" + str (s.total) + "Min")

output:
Xiao Ming: 330 points
———————-
Xiaohong: 330 points

summary

This is the end of this article about the implementation steps of functions using pybind11 to encapsulate C + + structures as parameters. For more information about pybind11 encapsulating C + + structure parameter functions, please search the previous articles of developpaer or continue to browse the relevant articles below. I hope you will support developpaer in the future!