C++程序调用python3

今天想做一个简单的管理密码的小程序,由于最近了解了下Python,就想用Python来写。但是看了看Python的界面库用法有感觉有点麻烦,所以还不如直接使用MFC写写界面,关于csv的文件处理部分使用Python来做,这样可能会简单些。

版本

vs使用2013版本

python使用3.6

notepad++配置python环境

https://www.cnblogs.com/huangsitao/p/10323198.html

VS中配置Python环境

1.在C++中调用Python需要包含“Python.h”头文件,通过everything搜索找到"Python.h",默认路径为C:UsersAdministratorAppDataLocalProgramsPythonPython36-32include

2.找到lib文件,我的是Python36.lib,默认路径为C:UsersAdministratorAppDataLocalProgramsPythonPython36-32libs

3.将include目录和libs目录拷贝一份保存到sln同级目录(因为在这个解决方案中我要写C++调用Python的程序)

4.在vs中对应的工程上右键->属性,C/C++->常规->附加包含目录填写include路径,链接器->常规->附加库目录填写lib路径,链接器->输入->附加依赖项填写python36.lib

5.main.cpp中编写下面代码,编译没有问题说明配置成功

1 #include<Python.h>
2 int main()
3 {
4      return 0;  
5 }

开始写代码

初始化

Py_Initialize(); //载入Python的内建模块并添加系统路径到模块搜索路径中。无返回值

检查是否初始化成功

Py_IsInitialized();

添加当前路径到系统路径中

PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");

PyRun_SimpleString为执行Python语句的函数。

加载python脚本文件

首先要写好pytest.py文件放到exe同级目录下。

pMoudle为NULL说明加载失败,失败的可能原因有:

1.找不到pytest.py文件,可能未将pytest.py文件拷贝到exe同级目录或者为设置当前路径为系统路径

2.pytest.py脚本有语法错误(我的就是这种原因,2.0和3.0的python语法不同,直接将别人的pytest代码拷贝过来未检查导致失败)

PyObject* pModule = PyImport_ImportModule("pytest");

获取到函数

PyObject* func = PyObject_GetAttrString(pModule, "add");

检查函数是否获取成功

if (!PyCallable_Check(func))
{
    std::cout << "not find add function." << std::endl;
    return -1;
}

设置调用函数的参数

调用Python函数,参数和返回值都必须为元组

PyObject* args = PyTuple_New(2);
PyObject* arg1 = PyLong_FromLong(4);
PyObject* arg2 = PyLong_FromLong(3);
PyTuple_SetItem(args, 0, arg1);
PyTuple_SetItem(args, 1, arg2);

调用函数

PyObject* pValue = PyObject_CallObject(func, args);

输出返回值

if (pValue != NULL)
{
    printf("Result of call: %ld
", PyLong_AsLong(pValue));
    Py_DECREF(pValue);
}

释放资源

Py_Finalize();

完整代码

 1 #include<iostream>
 2 #include<Python.h>
 3 
 4 int main()
 5 {
 6     Py_Initialize();
 7     // 检查初始化是否成功  
 8     if (!Py_IsInitialized()) {
 9         return -1;
10     }
11     // 添加当前路径,可以避免导入模块输入全路径
12     PyRun_SimpleString("import sys");
13     PyRun_SimpleString("print ('---import sys---')");
14     PyRun_SimpleString("sys.path.append('./')");
15     // 载入名为pytest的脚本  
16     PyObject* pModule = PyImport_ImportModule("pytest");
17     if (!pModule) // 加载模块失败
18     {
19         std::cout << "[ERROR] Python get module failed." << std::endl;
20         system("pause");
21         return 0;
22     }
23     std::cout << "[INFO] Python get module succeed." << std::endl;
24 
25     PyObject* func = PyObject_GetAttrString(pModule, "add");
26     if (!PyCallable_Check(func))
27     {
28         std::cout << "not find add function." << std::endl;
29         system("pause");
30         return -1;
31     }
32     PyObject* args = PyTuple_New(2);
33     PyObject* arg1 = PyLong_FromLong(4);
34     PyObject* arg2 = PyLong_FromLong(3);
35     PyTuple_SetItem(args, 0, arg1);
36     PyTuple_SetItem(args, 1, arg2);
37     PyObject* pValue = PyObject_CallObject(func, args);
38     if (pValue != NULL)
39     {
40         printf("Result of call: %ld
", PyLong_AsLong(pValue));
41         Py_DECREF(pValue);
42     }
43     else
44     {
45         Py_DECREF(func);
46         Py_DECREF(pModule);
47         PyErr_Print();
48         fprintf(stderr, "Call failed
");
49         return 1;
50     }
51     Py_Finalize();
52     system("pause");
53     return 0;
54 }

参考

https://docs.python.org/2/extending/embedding.html

https://www.cnblogs.com/yanzi-meng/p/8066944.html

原文地址:https://www.cnblogs.com/huangsitao/p/10323298.html