#include <Python.h>
#include <iostream>
int main() {
// 初始化Python解释器
Py_Initialize();
// 检查Python解释器是否成功初始化
if (!Py_IsInitialized()) {
std::cerr << "Failed to initialize Python interpreter" << std::endl;
return 1;
}
// 将当前工作目录添加到Python模块搜索路径中
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
// 导入Python模块
PyObject* pModule = PyImport_ImportModule("mymodule"); // 假设有一个名为mymodule的Python模块
if (pModule == NULL) {
PyErr_Print();
std::cerr << "Failed to load Python module" << std::endl;
return 1;
}
// 获取Python模块中的函数对象
PyObject* pFunc = PyObject_GetAttrString(pModule, "myfunction"); // 假设mymodule中有名为myfunction的函数
if (pFunc == NULL || !PyCallable_Check(pFunc)) {
PyErr_Print();
std::cerr << "Cannot find function in module" << std::endl;
Py_DECREF(pModule);
return 1;
}
// 调用Python函数,这里假设该函数不带参数且返回一个整数
PyObject* pValue = PyObject_CallObject(pFunc, NULL);
if (pValue == NULL) {
PyErr_Print();
std::cerr << "Function call failed" << std::endl;
Py_DECREF(pFunc);
Py_DECREF(pModule);
return 1;
}
// 获取Python函数的返回值
int result = -1;
if (PyLong_Check(pValue)) {
result = PyLong_AsLong(pValue);
} else {
std::cerr << "Return value is not an integer" << std::endl;
}
// 打印结果
std::cout << "Result from Python function: " << result << std::endl;
// 清理资源
Py_DECREF(pValue);
Py_DECREF(pFunc);
Py_DECREF(pModule);
// 关闭Python解释器
Py_Finalize();
return 0;
}
Py_Initialize() 函数来启动Python解释器。这是调用任何Python代码之前必须做的第一步。Py_IsInitialized() 检查解释器是否成功启动。PyRun_SimpleString() 将当前工作目录添加到Python模块搜索路径中,以便能够找到所需的Python模块。PyImport_ImportModule() 导入一个Python模块(例如 mymodule)。PyObject_GetAttrString() 获取模块中的函数对象(例如 myfunction),并检查它是否可调用。PyObject_CallObject() 调用Python函数,并传递参数(如果有)。这里假设该函数不带参数。Py_DECREF() 释放不再需要的Python对象,以避免内存泄漏。Py_Finalize() 关闭Python解释器。请确保你的环境中已经安装了Python开发库,并且编译时链接了相应的库文件。
上一篇:python 抓包
下一篇:sorted函数python用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站