Python有不少库,Qt用来编写界面,天然产生C++调用Python的需求。一路摸索,充满艰辛html
个人python头文件搜索路径:C:\Python27amd64\include
静态库在:C:\Python27amd64\libspython
//hello.py #!/usr/bin/env python # -*- coding: utf-8 -*- def xprint(): print("hello !!")
//main.cpp #include "Python.h" #include <iostream> using namespace std; int main(int argc, char *argv[]) { Py_Initialize();/* 开始Python解释器 */ PyRun_SimpleString("print 'python start'"); PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('C:\\Users\\Lution\\Documents\\moni\\py')"); // 导入hello.py模块 PyObject *pName = NULL; pName = PyString_FromString("hello"); PyObject *pmodule =NULL; pmodule = PyImport_Import(pName); //调用函数xprint() PyObject *pfunc = PyObject_GetAttrString(pmodule, "xprint"); PyObject_CallFunction(pfunc, NULL); Py_Finalize(); /* 结束Python解释器,释放资源 */ return 0; }
一、PyImport_Import或者PyImport_ImportModule老是返回为空
这个缘由是,python源代码要和C语言编译后的exe同目录,而不是与C源代码同目录
不然使用PyRun_SimpleString("sys.path.append('C:\\Users\\Lution\\Documents\\moni\\py')");
绝对路径指明python源代码位置,注意双斜杆。
注意这句PyRun_SimpleString("sys.path.append('./')");
添加的当前目录是指exe的当前目录,不是C源码目录ios
二、缺乏Python27_d.lib的解决方法
不要单纯地把Python27.lib伪形成Python27_d.lib,请修改Python.happ
//修改Python.h //修改前 #ifdef _DEBUG # define Py_DEBUG #endif
修改Python.h //修改后 #ifdef _DEBUG //# define Py_DEBUG #endif
修改Python.h //修改前 # ifdef _DEBUG # pragma comment(lib,"python27_d.lib") # else # pragma comment(lib,"python27.lib") # endif /* _DEBUG */
修改Python.h //修改后 # ifdef _DEBUG # pragma comment(lib,"python27.lib") # else # pragma comment(lib,"python27.lib") # endif /* _DEBUG */
//修改object.h //修改前 #if defined(Py_DEBUG) && !defined(Py_TRACE_REFS) #define Py_TRACE_REFS #endif
//修改object.h //修改后 #if defined(Py_DEBUG) && !defined(Py_TRACE_REFS) // #define Py_TRACE_REFS #endif
我发现程序执行的顺序出了点问题。在Py_Initialize();和Py_Finalize(); 之间的C语言代码会在Py_Finalize(); 以后执行函数