Home > php教程 > PHP开发 > body text

Embedding Python in C/C++

高洛峰
Release: 2016-11-23 13:47:47
Original
1554 people have browsed it

Embedding Python in C/C++ is also relatively simple. First, you need to add Python’s include file directory and lib file directory in VC:
Under VC6.0, open tools->options->directories->show directories for , add the inlude directory in the Python installation directory to the include files item, and add the libs directory to the library files item.
Under VC2005, open the tools->options->Projects and Solutions->VC++ directory, and then do the same work.

The code is as follows:

//在debug下执行出错,“无法找到python31_d.lib文件”,后查到原因是:在debug下生成必须要有python31_d.lib文件,否则只能在release下生成
#include <python.h>
int main()
{
    Py_Initialize();
    PyRun_SimpleString("Print &#39;hi, python!&#39;");
    Py_Finalize();
    return 0;
}
Copy after login

The prototype of the Py_Initialize function is: void Py_Initialize(). This function must be used when embedding a Python script. It initializes the Python interpreter. This function must be called before using other Python/C APIs. You can use the Py_IsInitialized function to determine whether the initialization is successful and return True if successful.
The prototype of the PyRun_SimpleString function is int PyRun_SimpleString(const char *command), which is used to execute a piece of Python code. Note: Do you need to maintain indentation between statements?
The prototype of the Py_Finalize function is void Py_Finalize(), which is used to close the Python interpreter and release the resources occupied by the interpreter.

The PyRun_SimpleFile function can be used to run ".py" script files. The function prototype is as follows:
int PyRun_SimpleFile(FILE *fp, const char *filename);
where fp is the open file pointer and filename is the python script file to be run. name. However, since the official release of this function is compiled by visual studio 2003.NET, if other versions of the compiler are used, the FILE definition may cause a crash due to version reasons. At the same time, for the sake of simplicity, you can use the following method to replace this function:
PyRun_SimpleString("execfile('file.py')"); Conversion processing into the corresponding data type in Python (in C language, all Python types are declared as PyObject types), the function prototype is as follows:
PyObject *Py_BuildValue(const char *format, …..);
PyString_String( ) is used to convert PyObject* type variables into char* type that can be processed by C language. The specific prototype is as follows:
char* PyString_String(PyObject *p);

List operation function:

PyObject * PyList_New(Py_ssize_t len);

int PyList_SetItem(PyObject *list, Py_ssize_t index, PyObject *item);
PyObject * PyList_GetItem(PyObject *list, Py_ssize_t index);
int PyList_Append(PyObject *list, PyObject *item);
int PyList_Sort(PyObject *list); Stint pylist_reverse (pyobject *list);
py_ssize_t pylist_size (pyobject *list); Item (pyobject *p, py_ssize_t pos, pyobject *o); PyObject * PyTuple_GetItem(PyObject *p, Py_ssize_t pos);
int _PyTuple_Resize(PyObject **p, Py_ssize_t newsize); //Note it is a ** pointer

Dictionary operation function:

PyObject * PyDict_New();

int PyDict_SetIt em(PyObject *p, PyObject *key, PyObject *val);
int PyDict_SetItemString(PyObject *p, const char *key, PyObject *val);
PyObject* PyDict_GetItem(PyObject *p, PyObject *key);
PyObject* PyDict_GetItemString(PyObject *p, const char *key);
//Corresponds to PyDict_SetItemString

int PyDict_DelItem(PyObject *p, PyObject *key);

int PyDict_DelItemString(PyObject *p, char *key);
//Corresponds to PyDict_SetItemString
int PyDict_Next (PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue);
PyObject* PyDict_Items(PyObject *p);
PyObject* PyDict_keys(PyObject *p);
PyObject* PyDict_Values(PyObject *p);

When using Python objects in C/C++, reference counting issues should be handled correctly, otherwise it can easily lead to memory leaks. When using functions in the Python/C API to create lists, tuples, dictionaries, etc., macros such as Py_CLEAR() and Py_DECREF() should be used to destroy these objects after completing operations on them. The prototype is as follows:
void Py_CLEAR(PyObject *o);
void Py_DECREF(PyObject *o);
Among them, for the Py_CLEAR function, the parameter can be a NULL pointer, which means no operation is performed, but the Py_DECREF function cannot be a NULL pointer, otherwise it will cause mistake.

Use the PyImport_Import() function to import a Python module in C and return a module object. The function prototype is:
PyObject* PyImport_Import(PyObject *name);
PyModule_GetDict() function can obtain the function list in the Python module and return a dictionary. The key in the dictionary is the function name and the value is the calling address of the function. The prototype is as follows:
PyObject* PyModule_GetDict(PyObject *module);
Use the PyObject_CallObject() function and the PyObject_CallFunction() function to call functions in Python in C. The prototype is as follows:
PyObject* PyObject_CallObject(PyObject *callable_object, PyObject *args) ;
//args is a tuple form
PyObject* PyObject_CallFunction(PyObject *callable, char *format, ...);
//format is a parameter type similar to "iss", followed by specified parameters
You can use PyCallable_Check(func ) to determine whether the function can be called, and returns True if it can.



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template