C++ 调用 Python3.6中的各种坑

使用Python3.6,在VS2013与VS2017中进行调用,其中的遇到了各种坑,将暂时遇到的坑先进行整理;

1:py文件不能以 test命名,不知道为什么,以test1,test2之类的命名都可以,但就是不能使用 test命名,否则,找不到函数名,即

    pFunc = PyObject_GetAttrString(pModule, "hello");该代码找不到 python 中的 hello()函数;

2:若 .py 文件中,有语法错误,则不能导入;

3:要导入.py文件所在的路径,如下所示:
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('F:\\C++ WorkSpace\\CallPython\\CallPython')");

其中,修改后的C++代码如下所示:

#include <Python.h>
#include <iostream>
#include <string>
using namespace std;


int main(int argc, char* argv[])

{

	//初始化python

	Py_Initialize();

	PyRun_SimpleString("import sys");
	PyRun_SimpleString("sys.path.append('F:\\C++ WorkSpace\\CallPython\\CallPython')");



	//定义python类型的变量

	PyObject *pModule = NULL;

	PyObject *pFunc = NULL;

	PyObject *pArg = NULL;

	PyObject *result = NULL;

	PyObject *pClass = NULL;

	PyObject *pInstance = NULL;

	PyObject *pDict = NULL;



	//直接运行python代码

	PyRun_SimpleString("print('python start')");

	//引入模块

	pModule = PyImport_ImportModule("test2");

	if (!pModule)
	{
		cout << "Import Module Failed" << endl;
		system("pause");
		return 0;
	}


	//获取模块字典属性
	pDict = PyModule_GetDict(pModule);

	////直接获取模块中的函数
	pFunc = PyObject_GetAttrString(pModule, "hello");

	//参数类型转换,传递一个字符串。将c/c++类型的字符串转换为python类型,元组中的python类型查看python文档
	pArg = Py_BuildValue("(s)", "hello charity");
	// 调用直接获得的函数,并传递参数
	PyEval_CallObject(pFunc, pArg);

	// 从字典属性中获取函数
	pFunc = PyDict_GetItemString(pDict, "arg");
	// 参数类型转换,传递两个整型参数
	pArg = Py_BuildValue("(i, i)", 1, 2);
	// 调用函数,并得到 python 类型的返回值
	result = PyEval_CallObject(pFunc, pArg);
	// c 用来保存 C/C++ 类型的返回值
	int c = 0;
	// 将 python 类型的返回值转换为 C/C++类型
	PyArg_Parse(result, "i", &c);
	cout << "a+b = " << c << endl;

	// 通过字典属性获取模块中的类 
	pClass = PyDict_GetItemString(pDict, "Test");

	if (!pClass)
	{
		cout << "获取模块中的类失败" << endl;
		system("pause");
		return 0;
	}

	// 实例化获取的类
	pInstance = PyInstanceMethod_New(pClass);

	//调用类的方法
	result = PyObject_CallMethod(pInstance, "say_hello", "(s,s)", "", "charity");

	//输出返回值
	char* name = NULL;
	PyArg_Parse(result, "s", &name);   //这个函数的第二个参数相当扯淡,具体看下文的英文,类型使用字符来表示的,例如“s”代表 str "i" 代表int,个人感觉相当扯淡

	printf("%s\n", name);

	PyRun_SimpleString("print('python end')");



	////释放python

	Py_Finalize();

	system("pause");

	return 0;

}

python代码:

def hello(s):
    print("hello world")
    print(s)


def arg(a, b):
    print('a=', a)
    print('b=', b)
    return a + b


class Test:
    def __init__(self):
        print("init")

    def say_hello(self, name):
        print("hello", name)
        return name

运行结果:

python start
hello world
hello charity
a= 1
b= 2
a+b = 3
hello charity
charity
python end
请按任意键继续. . .
 

猜你喜欢

转载自blog.csdn.net/lingtianyulong/article/details/81146495