c++调用Python首先安装Python,以win7为例,Python路径为:c:Python35,通过mingw编译c++代码。
编写makefile文件,首先要添加包含路径:
inc_path += c:/Python35/include
然后添加链接参数:
ld_flag += c:/Python35/libs/libpython35.a
在源文件中添加头文件引用:
#include "Python.h"
Python解释器需要进行初始化,完成任务后需要终止:
void start()
{
int r=Py_IsInitialized(); //1为已经初始化了
if (r==0)
{
//Py_SetPythonHome(L"C:Python35");
Py_Initialize(); //初始化
p_main_Module =PyImport_ImportModule("__main__");
if (!p_main_Module)
{
throw "";
}
}
}
void end()
{
Py_Finalize(); //清理
}
程序部署时可以将c:Python35lib目录复制到执行程序路径下,或者通过Py_SetPythonHome(L"C:Python35");设置Python的安装目录。
C++调用Python的基本需求:
1、运行Python指令
PyRun_SimpleString("print(os.getcwd(),a)");
pyext.eval(R"(a+='qwer')");
2、加载Python模块
PyObject * pModule =PyImport_ImportModule("tp"); //test:Python文件名,若脚本有错则返回空
PyRun_SimpleString("import os");
3、给Python的变量赋值
对于数值,使用Py_BuildValue:
Py_BuildValue("") None
Py_BuildValue("i", 123) 123
Py_BuildValue("iii", 123, 456, 789) (123, 456, 789)
Py_BuildValue("s", "hello") 'hello'
Py_BuildValue("ss", "hello", "world") ('hello', 'world')
Py_BuildValue("s#", "hello", 4) 'hell'
Py_BuildValue("()") ()
Py_BuildValue("(i)", 123) (123,)
Py_BuildValue("(ii)", 123, 456) (123, 456)
Py_BuildValue("(i,i)", 123, 456) (123, 456)
Py_BuildValue("[i,i]", 123, 456) [123, 456]
Py_BuildValue("{s:i,s:i}", "abc", 123, "def", 456) {'abc': 123, 'def': 456}
对于其他数据结构,使用相应的函数设置,例如:
PyObject *pArgs = PyTuple_New(1);
PyObject *pDict = PyDict_New(); //创建字典类型变量
PyDict_SetItemString(pDict, "Name", Py_BuildValue("s", "WangYao")); //往字典类型变量中填充数据
PyDict_SetItemString(pDict, "Age", Py_BuildValue("i", 25)); //往字典类型变量中填充数据
PyTuple_SetItem(pArgs, 0, pDict);//0---序号 将字典类型变量添加到参数元组中
构造好对象以后,通过PyObject_SetAttrString来设置进入Python中:
PyObject *ps=PyUnicode_DecodeUTF8(val,strlen(val),"ignore"); //构造了一个对象
PyObject_SetAttrString(p_main_Module,key,ps); //设置










