Brief introduction
Describes the initialization and exit of Python virtual machines, the creation of objects for Python basic data types, and the conversion of data types between C and Python.
Initialization and exit of Python virtual machines
The initialization of a Python virtual machine requires a call Py_Initialize()
to implement.
Py_IsInitialized()
Used to determine if the Python virtual machine initialization was successful, true is successful, and false is a failure.
The virtual machine must be initialized before calling Python in C + +.
Called when exiting the virtual machine Py_Finalize()
.
Exit the Python virtual machine when the process exits.
Instance:
#include <stdio.h>#include <Python.h>using namespace std;int main() { // 初始化Python虚拟机 Py_Initialize(); // 判断Python虚拟机是否成功 if (Py_IsInitialized() == 0){ printf("fal to initialize Python\n"); return -1; } printf("server start\n"); // 退出Python虚拟机 Py_Finalize(); return 0;}
Compiling methods and Parameters:
下面是Python2的编译方式,Python3的话,只需要将Python的库路径改成Python3的即可g++ -I/usr/include/python2.7 -c main.cppg++ -o main main.o -L/usr/local/lib -lpython2.7 -lrt -lpthread -lutil -ldl
Pyobject
All of the object types of Python are extensions of this type. This is a type that contains the information that Python needs to treat a pointer to an object as an object. In a normal release version, it contains only the reference count of the object and a pointer to the corresponding type object. Nothing is actually declared as Pyobject, but each pointer to a Python object can be converted to Pyobject *. You must use macros PY_REFCNT and Py_type to access members.
Macro description, not including all
Py_TYPE: 获取Python对象的数据类型Py_REFCNT: Python的引用计数器Py_SIZE: 获取Python数据大小还有很多...
Py_buildvalue
You can use it to convert all of the basic data types of C to data types that Python can access.
Description of the identifier:
S (str or none) [char *] uses ' utf-8 ' encoding to convert a null-terminated C string to a Python str object. If the C string pointer is null, none is represented. s# (str or none) [Char *,int] uses the ' utf-8 ' encoding to convert the C string and its length to a Python str object. If the C string pointer is null, the length is ignored to return none. Y (bytes) [char *] This converts the C string to a Python byte object. If the C string pointer is null, none is returned. y# (bytes) [Char *,int] This converts the C string and its length to a Python object. If the C string pointer is null, none is returned. Z (str or none) [char *] is the same as S. z# (str or none) [Char *,int] is the same as s#. U (str) [Py_unicode *] Converts a null-terminated buffer of Unicode (UCS-2 or UCS-4) data to a Python UNICODE object. If the Unicode buffer pointer is NULL, none is returned. u# (str) [Py_unicode *,int] Converts the Unicode (UCS-2 or UCS-4) data buffers and their lengths to Python Unicode objects. If the Unicode buffer pointer is null, the length is ignored and none is returned. U (str or none) [char *] is the same as S. u# (str or none) [Char *,int] is the same as s#. I (int) [INT] converts a normal c int to a Python integer object. b (int) [Char] converts a pure C char to a Python integer object. h (int) [short int] Converts a normal C short int to a Python integer object. L (int) [long int] Converts a c long int to a Python integer object. B (int) [unsigned char] converts c unsigned char to a Python integer object. H (int) [unsigned short int] Converts the c unsigned short int to a Python integer object. I (int) [unsigned int] converts c unsigned int to a Python integer object. K (int) [unsigned long] converts a C unsigned long to a Python integer object. L (int) [Long long] lon C longG is converted to a Python integer object. K (int) [unsigned long long] converts the C unsigned long long to a Python integer object. n (int) [py_ssize_t] converts C py_ssize_t to a python integer. C (bytes of length 1) [Char] converts the C int representing the bytes to a Python byte object of length 1. C (str of length 1) [int] converts the C int representing the character to a Python str object of length 1. D (float) [double] converts a C double to a python floating-point number. f (float) [float] converts C float to Python floating-point number. D (complex) [Py_complex *] Converts the C Py_complex structure to the Python plural. O (object) [Pyobject *] does not change the delivery of the Python object (except the reference count, which increases by 1). If the incoming object is a null pointer, it is assumed that this is because the call that produced the argument found an error and set an exception. Therefore, Py_buildvalue () returns null but does not throw an exception. If no exception has been thrown, set systemerror. S (object) [Pyobject *] is identical to O n ((object) [Pyobject *] and O, but does not increase the reference count of the object. It is useful to create an object by calling the object constructor in the argument list. O& (object) [converter, anything] converts any content to a Python object through a converter function. The function is called anything (should be compatible with void *) as its argument, and the "new" Python object should be returned, or null if an error occurs. (items) (tuple) [Matching-items] Converts a series of c values to a Python tuple with the same number of items. [Items] (list) [Matching-items] Converts a series of c values to a Python list with the same number of items. {Items} (dict) [Matching-items] Converts a series of c values to a Python dictionary. Each pair of consecutive C values is added to the dictionary as keys and values, respectively. If there is an error in the format string, set the systemerror exception and return null.
Create a Python object of the integer type
Use to Py_BuildValue
create an integer object.
void int_object(){ // 第一种方式 PyObject *py_ival = Py_BuildValue("i", -5987); // Python有符号整型 PyObject *py_ival2 = PyLong_FromLong(-8979); int ival = PyLong_AsLong(py_ival); // 把Python有字符整型转换成C的有字符整型 int ival2 = PyLong_AsLong(py_ival2); // 把Python有字符整型转换成C的有字符整型 printf("ival = %d, ival2 = %d\n", ival, ival2); // 第二种方式 PyObject *py_uval = Py_BuildValue("I", 465486); // Python无符号整型 PyObject *py_uval2 = PyLong_FromUnsignedLong(1654864); unsigned int uval = PyLong_AsUnsignedLong(py_uval); // 把Python无字符整型转换成C的无字符整型 unsigned int uval2 = PyLong_AsUnsignedLong(py_uval2); // 把Python无字符整型转换成C的无字符整型 printf("uval = %u, uval2 = %u\n", uval, uval2);}
To create a long-integer python object
void long_object(){ // 第一种方式 PyObject *py_lval = Py_BuildValue("L", 45648946484984); // Python 长整型 long long c_lval = PyLong_AsLongLong(py_lval); // 转换成C的长整型 printf("clval = %lld\n", c_lval); // 第二种方式 PyObject *py_lval2 = PyLong_FromLongLong(234234623454525); // PyLong_FromLongLong 使用方法定义一个Python长整型 long long c_lval2 = PyLong_AsLongLong(py_lval2); // 转换成C的长整型 printf("clval2 = %lld\n", c_lval2);}
Create a Python object of floating-point type
void double_object(){ // 第一种方式 float fval = 632.045; PyObject *py_fval = Py_BuildValue("d", fval); // Python 浮点类型 float c_fval = PyFloat_AsDouble(py_fval); // C的浮点类型 printf("fval = %f\n", c_fval); // 第二种方式 double dval = 48941546.578; PyObject *py_dval = PyFloat_FromDouble(dval); // Python 浮点类型 double c_dval = PyFloat_AsDouble(py_dval); // C的浮点类型 printf("c_dval = %lf\n", c_dval);}
Creating a Boolean type Object
void boolean_object(){ // 第一种方式 bool bval = true; // false 反之 PyObject *py_bval = Py_BuildValue("b", bval); // Python 布尔类型 int c_bval = PyInt_AsLong(py_bval); printf("c_bval = %d\n", c_bval); // 第二种方式 bool bval2 = false; PyObject *py_bval2 = PyBool_FromLong(bval2); // Python 布尔类型 int c_bval2 = PyInt_AsLong(py_bval2); printf("c_bval2 = %d\n", c_bval2);}
Create a Python string object
void string_object(){ // 第一种方式 const char *pstr = "this is a test"; PyObject *py_str = Py_BuildValue("s", pstr); // Python 字符串对象 char *c_pstr = PyString_AsString(py_str); // 转成C的字符指针 printf("c_pstr = %s\n", c_pstr); // 第二种方式 const char *pstr2 = "this is a test1"; PyObject *py_str2 = PyString_FromString(pstr2); // Python 字符串对象 char *c_pstr2 = PyString_AsString(py_str2); // 转成C的字符指针 printf("c_pstr2 = %s\n", c_pstr2); // 创建一个二进制的字符串对象 // 第一种方式 const int mem_len = 1024; char *mem = new char[mem_len]; PyObject *py_mem = Py_BuildValue("s#", mem, mem_len); // 1. 数据的类型 2. 指向数据的指针 3. 数据的长度 int c_data_len = PyString_Size(py_mem); printf("c_data_len = %d\n", c_data_len); // 第二种方式 PyObject *py_mem2 = PyString_FromStringAndSize(mem, mem_len); int c_data_len2 = PyString_Size(py_mem2); printf("c_data_len2 = %d\n", c_data_len2);}
Creating a Unicode string Object
void unicode_object(){ const char *p_ustr = "兰玉磊"; PyObject *py_unicode = PyUnicode_FromString(p_ustr); // 把C的字符串转成Python的unicode // 把unicode转成C的字符串 PyObject *py_utf8 = PyUnicode_AsUTF8String(py_unicode); // 把unicode转成utf-8 const char *c_string = PyString_AsString(py_utf8); // 把utf-8转成c的字符串 printf("c_utf8 = %s\n", c_string); // 格式化unicode字符串 // 创建一个unicode字符串 PyObject *py_unicode_fmt = PyUnicode_FromFormat("%s%d%s", "我今年", 18, "岁"); // 把unicode转C字符串 PyObject *py_utf8_fmt = PyUnicode_AsUTF8String(py_unicode_fmt); const char *utf8_fmt = PyString_AsString(py_utf8_fmt); printf("utf8_fmt = %s\n", utf8_fmt);}
Using Py_none
Py_None
is a global variable
PyObject* none_object(){ Py_RETURN_NONE; // 不需要自己return}
Main function
#include <stdio.h>#include <string.h>#include <stdlib.h>#include <Python.h>int main() { // 初始化Python虚拟机 Py_Initialize(); // 判断Python虚拟机是否成功 if (Py_IsInitialized() == 0){ printf("fal to initialize Python\n"); return -1; } printf("server start\n"); int_object(); long_object(); double_object(); boolean_object(); string_object(); unicode_object(); PyObject *py_ret = none_object(); if (py_ret == Py_None){ printf("is none object\n"); }else{ printf("is not none object\n"); } // 退出Python虚拟机 Py_Finalize(); return 0;}
A detailed description of the use of Python C APs (i)