参考:https://docs.python.org/3/c-api
https://blog.youkuaiyun.com/lingtianyulong/article/details/81146495
基础vs2015导入python包直接略过直接上代码:
c++代码:main.cpp
#include <Python.h>
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
//初始化python
Py_Initialize();
PyRun_SimpleString("import sys");
//此处不能设置当前main函数的同级目录
PyRun_SimpleString("sys.path.append('C:/Users/Administrator/Desktop')");
//定义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("mytest2");
//cout << "pModule:" << pModule << endl;
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);
//system("pause");
// 第二种方式从字典属性中获取函数
pFunc = PyDict_GetItemString(pDict, "arg");
// 参数类型转换,传递两个整型参数
pArg = Py_BuildValue("(i, i)", 1, 2);
// 调用函数,并得到 python 类型的返回值
result = PyEval_CallObject(pFunc, pArg);//注意:所有返回值都用PyObject指针对象接收
// c 用来保存 C/C++ 类型的返回值
int c = 0;
// 将 python 类型的返回值转换为 C/C++类型
PyArg_Parse(result, "i", &c);//对python返回值进行解析
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);
printf("%s\n", name);
PyRun_SimpleString("print('python end')");
释放python
Py_Finalize();
system("pause");
return 0;
}
python代码:mytest2.py
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
运行结果: