C语言调用Python 混合编程

导语

Python有很多库,Qt用来编写界面,自然产生C++调用Python的需求。一路摸索,充满艰辛

添加头文件搜索路径,导入静态库

我的python头文件搜索路径:C:\Python27amd64\include

静态库在:C:\Python27amd64\libs

简易示例

//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;
}

ERRORS

1、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源码目录

2、缺少Python27_d.lib的解决方法

不要单纯地把Python27.lib伪造成Python27_d.lib,请修改Python.h

//修改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(); 之后执行

参考博文

缺少Python27_d.lib

PyImport_ImportModule总是返回为空