Boost.Python implements Python objects and various types of built-in operations and methods

Explain that
Python has a variety of very useful data types, such as Numbers, String, List, Tuple, Dictionary and Set. Numbers and String (their content) we often use in the previous examples can be directly used in C++ code, because they are also C++ data types (although the implementation is different, it does not prevent the two from being common). But other types of data structures are not available in C++, so what should Python do when it needs to use these types and interact with C++ code?

From the point of view of Boost.Python and C++, these Pythonic variables are just instances of class objects. Every variable or method of Python is a Python object, which has various attributes, and Python has given these objects built-in methods of one kind or another, so that we can use them conveniently. The Boost.Python library provides a class called object that wraps a valid Python object and provides a Python-like interface. In other words, each Python object can be used as an object class instance of Boost.Python, and Boost.Python provides support for the operation of this instance close to Python syntax, and these supports are mainly implemented in the form of operator overloading. for example:

Python C++ description
y = x.foo y = x.attr("foo"); Get the attribute value of x, usually a member variable
x.foo = 1 x.attr("foo") = 1; Set the attribute y of
x = x[z] y = x[z]; list/dict operation
x[z] = 1 x[z] = 1; list/dict operation
y = x[3:-1] y = x.slice(3, -1); slice operation
y = x[3:] ​​y = x.slice(3,_);    
y = x[:-2] y = x.slice(_,-2);    
z = x(1, y) z = x(1, y); call function
z = xf(1, y) z = x.attr(“f”)(1, y); call member function
not x !x logical not
x and y x && One of the goals of ylogic and
Boost.Python is to provide a bidirectional mapping between C++ and Python while maintaining a Python feel. Boost.Python C++ objects are as close to Python as possible. In the operation examples in the above table, although they are not completely consistent, Boost.Python tries to provide functions that conform to C++ syntax and Python functions.

The above Python data types, except Set, are treated as instances of a class by Boost.Python. How to understand it, for example, a Python variable a = [1,2,3,4] is a List type, then a is a class list instance in Boost.Python.

The Object class is a base class that provides common operation methods for all Python objects. For Python's commonly used data types, Boost.Python provides object-based derived classes corresponding to Python types:

list
dict
tuple
str
long_
enum
Note: currently does not contain the Set type.

The relationship between these derived classes and the base class is as follows:

For the encapsulation of Python objects, Boost.Python proposes two encapsulation concepts: ObjectWrapper and TypeWrapper, the former is used to describe the objects that manage Python, and the latter is optimized and improved for specific Python objects.


ObjectWrapper
ObjectWrapper defines two concepts for describing classes that manage Python orientations and is intended to support the use of a Python-like syntax.

The ObjectWrapper concept models object as a common base class and is used to provide special constructors or other functionality through member functions. Unless the return type R is itself a TypeWrapper, it is a member function call of the form.
such as statement
 

x.some_function(a1, a2,...an)

Equivalent to:

extract<R>(x.attr("some_function")(object(a1), object(a2),...object(an)))()

TypeWrapper

TypeWrapper is an improvement over ObjectWrapper that is associated with a specific Python type X . For a given TypeWrapper T, valid constructor expressions are:

T(a1, a2,...an)

Constructs a new T object managing the result of calling X with parameters corresponding to:

object(a1), object(a2),...object(an)

When used as an argument to a wrapped C++ function or as a template argument to extract<>, only instances of the associated Python type are considered matches.

Warning
When the return type is TypeWrapper, the result of the special member function call is that the returned object may not match the type of the specific Python object. Usually this is not a serious problem; the worst result is that the error is detected at runtime. The time will be slightly later than in other cases. For an example of how this happens, note that the dict member function items returns an object of type list. Now suppose the user defines this dict subclass in Python:
 

>>> class mydict(dict):
...     def items(self):
...         return tuple(dict.items(self)) # return a tuple

 

由于 mydict 的实例是 dict 的实例,因此当用作包装 C++ 函数的参数时,boost::python::dict 可以接受 Python 类型 mydict 的对象。在这个对象上调用 items() 可以导致 boost::python::list 的实例,它实际上包含一个 Python 元组。随后尝试在此对象上使用列表方法(例如追加或任何其他变异操作)将引发与尝试从 Python 执行此操作时发生的相同异常。

The Object base class
The Object class is the wrapper class for generic Python objects and the base class for other TypeWrapper classes. object has a templated constructor that converts any C++ object to Python using the same underlying mechanism as the argument to call<>. If an object instance is created without any constructor parameters, then the value of this instance is None.

The object class wraps a PyObject*. All the complexities of dealing with PyObjects, such as managing reference counts, are handled by the object class. Boost.Python C++ objects can be explicitly constructed from virtually any C++ object.

Let's start with a simple example, this Python code snippet:
 

def f(x, y):
     if (y == 'foo'):
         x[3:7] = 'bar'
     else:
         x.items += y(3, x)
     return x

def getfunc():
   return f;

Can be rewritten in C++ using the Boost.Python tools in the following way:

object f(object x, object y) {
     if (y == "foo")
         x.slice(3,7) = "bar";
     else
         x.attr("items") += y(3, x);
     return x;
}
object getfunc() {
    return object(f);
}

Aside from the visual differences due to the fact that we code in C++, the look and feel should be immediately apparent to Python coders.

See blog for more details

Boost(8): Boost.Python implements Python objects and various types of built-in operations and methods_Xiangdi Blog-CSDN Blog_boost python

Guess you like

Origin blog.csdn.net/qq_38563206/article/details/126366792