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總是返回為空


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM