C++调用python脚本程序示例

环境

windows系统下,QT(MinGW) + python 3.7开发环境。(详细用法可以参考官方的C/python官方接口文档)。

配置

这里只需要添加python的头文件和库函数就好了,代码如下:

INCLUDEPATH += D:/softwareinstallpath/python378/include

LIBS += -LD:/softwareinstallpath/python378/libs -lpython37

测试代码

如果python的第三方库(numpy、PIL等用不了),需要添加代码(前提是你的python环境中有这个第三方库):

PyRun_SimpleString(“import sys”);
PyRun_SimpleString(“sys.path.append(‘脚本文件路径’)”);
PyRun_SimpleString(“sys.path.append(‘C:/Users/a/.conda/envs/paddlex_3.7/Lib/site-packages’)”);

#include <Python.h>
#include <QCoreApplication>

#include <string>
#include <codecvt>

#if 1
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    // 初始化Python
    //在使用Python系统前,必须使用Py_Initialize对其
    //进行初始化。它会载入Python的内建模块并添加系统路
    //径到模块搜索路径中。这个函数没有返回值,检查系统
    //是否初始化成功需要使用Py_IsInitialized。

    Py_Initialize();

    // 检查初始化是否成功
    if ( !Py_IsInitialized() )
    {
        return -1;
    }

    // 添加当前路径
    //把输入的字符串作为Python代码直接运行,返回0
    //表示成功,-1表示有错。大多时候错误都是因为字符串
    //中有语法错误。
    PyRun_SimpleString("print(4+5)");
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");
    PyObject *pName,*pModule,*pDict,*pFunc,*pArgs,*pValue;


    std::wstring str = L"test_C_To_Python";

    //std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;

    //std::string  sr= conv.to_bytes(str);
    std::string  sr= "test_C_To_Python";
    // 载入名为pytest的脚本
    pName = PyUnicode_FromUnicode(str.c_str(),str.size());

    //pName = PyString_FromString("pytest");
    pModule = PyImport_ImportModule(sr.c_str());

    //pModule = PyImport_Import(pName);
    if (!pModule)
    {
        printf("can't find pytest.py");
        getchar();
        return -1;
    }
    pDict = PyModule_GetDict(pModule);
    if ( !pDict )
    {
        return -1;
    }

    // 找出函数名为add的函数
    pFunc = PyDict_GetItemString(pDict, "add");
    if ( !pFunc || !PyCallable_Check(pFunc) )
    {
        printf("can't find function [add]");
        getchar();
        return -1;
    }

    // 参数进栈
    pArgs = PyTuple_New(2);

    //  PyObject* Py_BuildValue(char *format, ...)
    //  把C++的变量转换成一个Python对象。当需要从
    //  C++传递变量到Python时,就会使用这个函数。此函数
    //  有点类似C的printf,但格式不同。常用的格式有
    //  s 表示字符串,
    //  i 表示整型变量,
    //  f 表示浮点数,
    //  O 表示一个Python对象。

    PyTuple_SetItem(pArgs, 0, Py_BuildValue("l",3));
    PyTuple_SetItem(pArgs, 1, Py_BuildValue("l",4));

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

    //下面这段是查找函数foo 并执行foo
    pFunc = PyDict_GetItemString(pDict, "foo");
    if ( !pFunc || !PyCallable_Check(pFunc) )
    {
        printf("can't find function [foo]");
        getchar();
        return -1;
    }

    pArgs = PyTuple_New(1);
    PyTuple_SetItem(pArgs, 0, Py_BuildValue("l",2)); //

    PyObject_CallObject(pFunc, pArgs);


    Py_DECREF(pName);
    Py_DECREF(pArgs);
    Py_DECREF(pModule);

    // 关闭Python
    Py_Finalize();

    system("pause");

    return a.exec();
}
#else
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    // 初始化Python
    //在使用Python系统前,必须使用Py_Initialize对其
    //进行初始化。它会载入Python的内建模块并添加系统路
    //径到模块搜索路径中。这个函数没有返回值,检查系统
    //是否初始化成功需要使用Py_IsInitialized。

    Py_Initialize();

    // 检查初始化是否成功
    if ( !Py_IsInitialized() )
    {
        //return qDebug<<"chush";
    }

    // 添加当前路径
    //把输入的字符串作为Python代码直接运行,返回0
    //表示成功,-1表示有错。大多时候错误都是因为字符串
    //中有语法错误。
//    PyRun_SimpleString("print(4+5)");
    PyRun_SimpleString("import sys");
    //PyRun_SimpleString("sys.path.append('./')");
    PyRun_SimpleString("sys.path.append('D:/softwareworkspace/QT/CToPython36')");
    PyRun_SimpleString("D:/softwareinstallpath/python378/libs/python37.lib");
    PyObject *pName,*pModule,*pDict,*pFunc,*pArgs,*pValue;

    std::string  sr= "crop";

    pModule = PyImport_ImportModule(sr.c_str());
    printf("******==%s==******\n",sr.c_str());

    if (!pModule)
    {
        printf("can't find Antibody-image-crop.py");
        getchar();
        return -1;
    }
    pDict = PyModule_GetDict(pModule);
    if ( !pDict )
    {
        return -1;
    }

    // 找出函数名为add的函数
    pFunc = PyDict_GetItemString(pDict, "cropFunc");
    if ( !pFunc || !PyCallable_Check(pFunc) )
    {
        printf("can't find function [cropFunc]");
        getchar();
        return -1;
    }
    // 参数进栈
    pArgs = PyTuple_New(1);
    //  PyObject* Py_BuildValue(char *format, ...)
    //  把C++的变量转换成一个Python对象。当需要从
    //  C++传递变量到Python时,就会使用这个函数。此函数
    //  有点类似C的printf,但格式不同。常用的格式有
    //  s 表示字符串,
    //  i 表示整型变量,
    //  f 表示浮点数,
    //  O 表示一个Python对象。

    PyTuple_SetItem(pArgs, 0, Py_BuildValue("s","/home/zhangsong/saiweier/PythonToC/data"));

    // 调用Python函数
    //PyObject *pcrop = PyObject_CallObject(pFunc, pArgs);
    PyObject *pcrop = PyObject_Call(pFunc, pArgs,NULL);
    char * result;
    PyArg_Parse(pcrop, "s", &result);
    printf("python object to C++ = %s\n;",result);
    printf("Py_ABS(-1) = %d\n;",Py_ABS(-1));
    /*
    int num;
    if (!PyArg_ParseTuple((PyObject *)(PyObject_CallObject(pFunc, pArgs)), "i", &num))
    {
        printf("python object to C++ error\n");
        return a.exec();
    }else
    {
        printf("python object to C++ = %d\n;",num);
    }
    */

    Py_DECREF(pName);
    Py_DECREF(pArgs);
    Py_DECREF(pModule);

    // 关闭Python
    Py_Finalize();

    system("pause");

    return a.exec();
}
#endif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值