版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
int test03()
{
Py_Initialize();//使用python之前,要调用Py_Initialize();这个函数进行初始化
if (!Py_IsInitialized())
{
printf("初始化失败!");
return 0;
}
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");//这一步很重要,修改Python路径
PyObject * pModule = NULL;//声明变量
PyObject * pFunc = NULL;// 声明变量
PyObject * pClass = NULL;//声明变量
PyObject * pInstance = NULL;
pModule = PyImport_ImportModule("pythonTest");//这里是要调用的文件名hello.py
if (pModule == NULL)
{
cout << "没找到" << endl;
}
// 模块的字典列表
PyObject* pDict = PyModule_GetDict(pModule);
if (!pDict) {
printf("Cant find dictionary./n");
return -1;
}
//获取calc类
PyObject* pClassCalc = PyDict_GetItemString(pDict, "calc");
if (!pClassCalc) {
printf("Cant find calc class./n");
return -1;
}
//构造Person的实例
PyObject* pInstanceCalc = PyInstanceMethod_New(pClassCalc);
if (!pInstanceCalc) {
printf("Cant find calc instance./n");
return -1;
}
PyObject* pRet = PyObject_CallMethod(pClassCalc,"add","10","10", pInstanceCalc);
if (!pRet)
{
printf("不能找到 pRet");
return -1;
}
int res = 0;
PyArg_Parse(pRet, "i", &res);//转换返回类型
cout << "res:" << res << endl;//输出结果
//释放
/*Py_DECREF(pClassCalc);
Py_DECREF(pInstanceCalc);
Py_DECREF(pModule);*/
Py_Finalize(); // 与初始化对应
system("pause");
return 0;
}