# Python嵌入(Python Embedding)示例代码
# 这个例子展示了如何在C/C++程序中嵌入Python解释器。
# 假设我们有一个简单的C++程序,它需要调用Python代码来执行某些任务。
#include <Python.h>
int main(int argc, char *argv[]) {
wchar_t *program = Py_DecodeLocale(argv[0], NULL);
if (program == NULL) {
fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
exit(1);
}
Py_SetProgramName(program); // Pass the program name in Unicode format
Py_Initialize();
PyRun_SimpleString("print('Hello from embedded Python!')");
// 调用一个更复杂的Python函数
PyObject *pName, *pModule, *pDict, *pFunc;
PyObject *pArgs, *pValue;
// 加载Python模块
pName = PyUnicode_DecodeFSDefault("example"); // 模块名
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule, "my_function"); // 获取模块中的函数
if (pFunc && PyCallable_Check(pFunc)) {
pArgs = PyTuple_New(1);
pValue = PyLong_FromLong(42); // 创建参数
if (!pValue) {
Py_DECREF(pArgs);
Py_DECREF(pModule);
fprintf(stderr, "Cannot convert argument\n");
return 1;
}
PyTuple_SetItem(pArgs, 0, pValue);
pValue = PyObject_CallObject(pFunc, pArgs); // 调用函数
Py_DECREF(pArgs);
if (pValue != NULL) {
printf("Result of call: %ld\n", PyLong_AsLong(pValue));
Py_DECREF(pValue);
} else {
Py_DECREF(pFunc);
Py_DECREF(pModule);
PyErr_Print();
fprintf(stderr, "Call failed\n");
return 1;
}
} else {
if (PyErr_Occurred())
PyErr_Print();
fprintf(stderr, "Cannot find function \"my_function\"\n");
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
} else {
PyErr_Print();
fprintf(stderr, "Failed to load \"%s\"\n", "example");
return 1;
}
Py_Finalize();
PyMem_RawFree(program);
return 0;
}
Py_Initialize() 初始化Python解释器。PyRun_SimpleString() 直接运行一段简单的Python代码。PyImport_Import() 加载Python模块,并使用 PyObject_GetAttrString() 获取模块中的函数。PyObject_CallObject() 调用函数。Py_DECREF() 和 Py_Finalize() 清理资源并关闭解释器。这个示例展示了如何在C++程序中嵌入Python解释器,并与Python代码进行交互。
上一篇:python判断整数
下一篇:python 窗口
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站