Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++调用python

作者:浪子无家   发布日期:2025-09-15   浏览:90

#include <Python.h>
#include <iostream>

int main() {
    // 初始化Python解释器
    Py_Initialize();

    // 检查Python解释器是否初始化成功
    if (Py_IsInitialized()) {
        std::cout << "Python Interpreter Initialized" << std::endl;

        // 创建一个Python代码字符串
        const char* python_code = "print('Hello from Python!')";

        // 使用PyRun_SimpleString执行Python代码
        PyRun_SimpleString(python_code);

        // 调用Python函数并获取返回值
        PyObject* pModule = NULL;
        PyObject* pFunc = NULL;
        PyObject* pValue = NULL;

        // 导入Python模块
        pModule = PyImport_ImportModule("math");

        if (pModule != NULL) {
            // 获取Python模块中的函数
            pFunc = PyObject_GetAttrString(pModule, "sqrt");

            if (pFunc && PyCallable_Check(pFunc)) {
                // 构建参数列表
                PyObject* pArgs = PyTuple_New(1);
                PyTuple_SetItem(pArgs, 0, PyFloat_FromDouble(16.0));

                // 调用Python函数
                pValue = PyObject_CallObject(pFunc, pArgs);
                PyTuple_Clear(pArgs);

                if (pValue != NULL) {
                    std::cout << "Result of sqrt(16): " << PyFloat_AsDouble(pValue) << std::endl;
                    Py_DECREF(pValue);
                } else {
                    PyErr_Print();
                }
            } else {
                if (PyErr_Occurred())
                    PyErr_Print();
            }

            Py_XDECREF(pFunc);
            Py_DECREF(pModule);
        } else {
            PyErr_Print();
        }
    } else {
        std::cout << "Failed to initialize Python Interpreter" << std::endl;
    }

    // 关闭Python解释器
    Py_Finalize();

    return 0;
}

解释说明:

  1. 初始化Python解释器:使用Py_Initialize()来启动Python解释器。
  2. 检查初始化状态:通过Py_IsInitialized()确认解释器是否成功启动。
  3. 执行Python代码:使用PyRun_SimpleString可以直接执行一段Python代码。
  4. 导入Python模块:使用PyImport_ImportModule导入Python模块(例如math)。
  5. 获取Python函数:使用PyObject_GetAttrString从模块中获取特定的函数(例如sqrt)。
  6. 构建参数列表:使用PyTuple_NewPyTuple_SetItem创建参数列表。
  7. 调用Python函数:使用PyObject_CallObject调用Python函数,并处理返回值。
  8. 错误处理:使用PyErr_Print打印Python错误信息。
  9. 释放资源:使用Py_DECREFPy_XDECREF释放不再需要的对象。
  10. 关闭Python解释器:使用Py_Finalize关闭Python解释器。

这个示例展示了如何在C++程序中嵌入Python解释器,执行Python代码以及调用Python模块中的函数。

上一篇:python重命名文件

下一篇:python中def

大家都在看

python时间格式

python读取文件路径

staticmethod在python中有

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站