This article mainly introduces the introduction of two types of functions commonly used in Python embedding at a lower level, as well as the actual application steps of the two types of functions and the specific introduction of the relevant code, the following is a detailed description of the article. I hope you will get what you want after browsing.
In the example in the previous section, only simple functions are used to embed Python into the C language. However, if you need to use a Python script to PASS Parameters in the C program or obtain the return value of the Python script, you need to use more functions to compile the C program. Because Python has its own data type, special APIs should be used in the C program to operate the corresponding data type. Common functions are as follows.
1. Processing numbers and strings
The Python/c api provides the Py_BuildValue () function to convert numbers and strings to the corresponding data type in Python. The function prototype is as follows.
- PyObject* Py_BuildValue( const char *format, ...)
The parameter meanings are as follows.
· Format: format the string, as shown in Table 8-1.
- Py_BuildValue()
The remaining parameters in the function are integer, floating point, or string values in the C language to be converted. The returned value is a pointer of the PyObject type. In C, all Python types are declared as PyObject.
2. List operations
Python/c api provides the PyList_New () function to create a new Python list. The Return Value of the PyList_New () function is the list created. The function prototype is as follows.
- PyObject* PyList_New( Py_ssize_t len)
The parameter meanings are as follows.
· Len: the length of the created list.
After the list is created, you can use the PyList_SetItem () function to add items to the list. The function prototype is as follows.
- int PyList_SetItem( PyObject *list,
Py_ssize_t index, PyObject *item)
The parameter meanings are as follows.
· List: list of items to be added.
· Index: Location index of the added item.
· Item: the value of the added item.
You can also use the PyList_GetItem () function in Python/c api to obtain the value of an item in the list. The value returned by the PyList_GetItem () function. The function prototype is as follows.
- PyObject* PyList_GetItem
( PyObject *list, Py_ssize_t index)
The above section describes the commonly used functions embedded in lower layers of Python.