如何實現 C/C++ 與 Python 的通訊?


屬於混合編程的問題。較全面的介紹一下,不只限於題主提出的問題。
如下討論中,Python指它的標準實現,即CPython(雖然不是很嚴格)html

本文分4個部分node

1. C/C++ 調用 Python (基礎篇)— 僅討論Python官方提供的實現方式
2. Python 調用 C/C++ (基礎篇)— 僅討論Python官方提供的實現方式
3. C/C++ 調用 Python (高級篇)— 使用 Cython
4. Python 調用 C/C++ (高級篇)— 使用 SWIGpython

練習本文中的例子,須要搭建Python擴展開發環境。具體細節見[搭建Python擴展開發環境 - 蛇之魅惑 - 知乎專欄](http://zhuanlan.zhihu.com/python-dev/20150730)c++

**1 C/C++ 調用 Python(基礎篇)**
Python 自己就是一個C庫。你所看到的可執行體python只不過是個stub。真正的python實體在動態連接庫裏實現,在Windows平臺上,這個文件位於 %SystemRoot%\System32\python27.dll。編程

你也能夠在本身的程序中調用Python,看起來很是容易:api

```
//my_python.c
#include <Python.h>bash

int main(int argc, char *argv[])
{
Py_SetProgramName(argv[0]);
Py_Initialize();
PyRun_SimpleString("print 'Hello Python!'\n");
Py_Finalize();
return 0;
}數據結構

```app

在Windows平臺下,打開Visual Studio命令提示符,編譯命令爲python2.7

```
cl my_python.c -IC:\Python27\include C:\Python27\libs\python27.lib

```

在Linux下編譯命令爲

```
gcc my_python.c -o my_python -I/usr/include/python2.7/ -lpython2.7

```

在Mac OS X 下的編譯命令同上

產生可執行文件後,直接運行,結果爲輸出

```
Hello Python!

```

Python庫函數PyRun_SimpleString能夠執行字符串形式的Python代碼。

雖然很是簡單,但這段代碼除了能用C語言動態生成一些Python代碼以外,並無什麼用處。咱們須要的是C語言的數據結構可以和Python交互。

下面舉個例子,好比說,有一天咱們用Python寫了一個功能特別強大的函數:

```
def great_function(a):
return a + 1
```

接下來要把它包裝成C語言的函數。咱們期待的C語言的對應函數應該是這樣的:

```
int great_function_from_python(int a) {
int res;
// some magic
return res;
}
```

首先,複用Python模塊得作‘import’,這裏也不例外。因此咱們把great_function放到一個module裏,好比說,這個module名字叫 great_module.py

接下來就要用C來調用Python了,完整的代碼以下:

```
#include <Python.h>

int great_function_from_python(int a) {
int res;
PyObject *pModule,*pFunc;
PyObject *pArgs, *pValue;

/* import */
pModule = PyImport_Import(PyString_FromString("great_module"));

/* great_module.great_function */
pFunc = PyObject_GetAttrString(pModule, "great_function");

/* build args */
pArgs = PyTuple_New(1);
PyTuple_SetItem(pArgs,0, PyInt_FromLong(a));

/* call */
pValue = PyObject_CallObject(pFunc, pArgs);

res = PyInt_AsLong(pValue);
return res;
}
```

從上述代碼能夠窺見Python內部運行的方式:

* 全部Python元素,module、function、tuple、string等等,實際上都是PyObject。C語言裏操縱它們,一概使用PyObject *。
* Python的類型與C語言類型能夠相互轉換。Python類型XXX轉換爲C語言類型YYY要使用PyXXX_AsYYY函數;C類型YYY轉換爲Python類型XXX要使用PyXXX_FromYYY函數。
* 也能夠建立Python類型的變量,使用PyXXX_New能夠建立類型爲XXX的變量。
* 若a是Tuple,則a[i] = b對應於 PyTuple_SetItem(a,i,b),有理由相信還有一個函數PyTuple_GetItem完成取得某一項的值。
* 不只Python語言很優雅,Python的庫函數API也很是優雅。

如今咱們獲得了一個C語言的函數了,能夠寫一個main測試它

```
#include <Python.h>

int great_function_from_python(int a);

int main(int argc, char *argv[]) {
Py_Initialize();
printf("%d",great_function_from_python(2));
Py_Finalize();
}
```

編譯的方式就用本節開頭使用的方法。

在Linux/Mac OSX運行此示例以前,可能先須要設置環境變量:

bash:

```
export PYTHONPATH=.:$PYTHONPATH
```

csh:

```
setenv PYTHONPATH .:$PYTHONPATH
```

**2 Python 調用 C/C++(基礎篇)**
這種作法稱爲Python擴展。
好比說,咱們有一個功能強大的C函數:

```
int great_function(int a) {
return a + 1;
}

```

指望在Python裏這樣使用:

```
>>> from great_module import great_function
>>> great_function(2)
3
```

考慮最簡單的狀況。咱們把功能強大的函數放入C文件 great_module.c 中。

```
#include <Python.h>

int great_function(int a) {
return a + 1;
}

static PyObject * _great_function(PyObject *self, PyObject *args)
{
int _a;
int res;

if (!PyArg_ParseTuple(args, "i", &_a))
return NULL;
res = great_function(_a);
return PyLong_FromLong(res);
}

static PyMethodDef GreateModuleMethods[] = {
{
"great_function",
_great_function,
METH_VARARGS,
""
},
{NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC initgreat_module(void) {
(void) Py_InitModule("great_module", GreateModuleMethods);
}
```

除了功能強大的函數great_function外,這個文件中還有如下部分:

* 包裹函數_great_function。它負責將Python的參數轉化爲C的參數(PyArg_ParseTuple),調用實際的great_function,並處理great_function的返回值,最終返回給Python環境。
* 導出表GreateModuleMethods。它負責告訴Python這個模塊裏有哪些函數能夠被Python調用。導出表的名字能夠隨便起,每一項有4個參數:第一個參數是提供給Python環境的函數名稱,第二個參數是_great_function,即包裹函數。第三個參數的含義是參數變長,第四個參數是一個說明性的字符串。導出表老是以{NULL, NULL, 0, NULL}結束。
* 導出函數initgreat_module。這個的名字不是任取的,是你的module名稱添加前綴init。導出函數中將模塊名稱與導出表進行鏈接。

在Windows下面,在Visual Studio命令提示符下編譯這個文件的命令是

```
cl /LD great_module.c /o great_module.pyd -IC:\Python27\include C:\Python27\libs\python27.lib

```

/LD 即生成動態連接庫。編譯成功後在當前目錄能夠獲得 great_module.pyd(其實是dll)。這個pyd能夠在Python環境下直接看成module使用。

在Linux下面,則用gcc編譯:

```
gcc -fPIC -shared great_module.c -o great_module.so -I/usr/include/python2.7/ -lpython2.7
```

在當前目錄下獲得great_module.so,同理能夠在Python中直接使用。

**本部分參考資料**

* 《Python源碼剖析-深度探索動態語言核心技術》是系統介紹CPython實現以及運行原理的優秀教程。
* Python 官方文檔的這一章詳細介紹了C/C++與Python的雙向互動[Extending and Embedding the Python Interpreter](https://link.zhihu.com/?target=https%3A//docs.python.org/2/extending/index.html%23extending-index)
* 關於編譯環境,本文所述方法僅爲出示原理所用。規範的方式以下:[3\. Building C and C++ Extensions with distutils](https://link.zhihu.com/?target=https%3A//docs.python.org/2/extending/building.html%23building)
* 做爲字典使用的官方參考文檔 [Python/C API Reference Manual](https://link.zhihu.com/?target=https%3A//docs.python.org/2/c-api/index.html%23c-api-index)

用以上的方法實現C/C++與Python的混合編程,須要對Python的內部實現有至關的瞭解。接下來介紹當前較爲成熟的技術Cython和SWIG。

**3 C/C++ 調用 Python(使用Cython)**
在前面的小節中談到,Python的數據類型和C的數據類型貌似是有某種「一一對應」的關係的,此外,因爲Python(確切的說是CPython)自己是由C語言實現的,故Python數據類型之間的函數運算也必然與C語言有對應關係。那麼,有沒有可能「自動」的作替換,把Python代碼直接變成C代碼呢?答案是確定的,這就是Cython主要解決的問題。

安裝Cython很是簡單。Python 2.7.9以上的版本已經自帶easy_install:

```
easy_install -U cython

```

在Windows環境下依然須要Visual Studio,因爲安裝的過程須要編譯Cython的源代碼,故上述命令須要在Visual Studio命令提示符下完成。一下子使用Cython的時候,也須要在Visual Studio命令提示符下進行操做,這一點和第一部分的要求是同樣的。

繼續以例子說明:

```
#great_module.pyx
cdef public great_function(a,index):
return a[index]

```

這其中有非Python關鍵字cdef和public。這些關鍵字屬於Cython。因爲咱們須要在C語言中使用「編譯好的Python代碼」,因此得讓great_function從外面變得可見,方法就是以「public」修飾。而cdef相似於Python的def,只有使用cdef纔可使用Cython的關鍵字public。

這個函數中其餘的部分與正常的Python代碼是同樣的。

接下來編譯 great_module.pyx

```
cython great_module.pyx

```

獲得great_module.h和great_module.c。打開great_module.h能夠找到這樣一句聲明:

```
__PYX_EXTERN_C DL_IMPORT(PyObject) *great_function(PyObject *, PyObject *)
```

寫一個main使用great_function。注意great_function並不規定a是何種類型,它的功能只是提取a的第index的成員而已,故使用great_function的時候,a能夠傳入Python String,也能夠傳入tuple之類的其餘可迭代類型。仍然使用以前提到的類型轉換函數PyXXX_FromYYY和PyXXX_AsYYY。

```
//main.c
#include <Python.h>
#include "great_module.h"

int main(int argc, char *argv[]) {
PyObject *tuple;
Py_Initialize();
initgreat_module();
printf("%s\n",PyString_AsString(
great_function(
PyString_FromString("hello"),
PyInt_FromLong(1)
)
));
tuple = Py_BuildValue("(iis)", 1, 2, "three");
printf("%d\n",PyInt_AsLong(
great_function(
tuple,
PyInt_FromLong(1)
)
));
printf("%s\n",PyString_AsString(
great_function(
tuple,
PyInt_FromLong(2)
)
));
Py_Finalize();
}
```

編譯命令和第一部分相同:
在Windows下編譯命令爲

```
cl main.c great_module.c -IC:\Python27\include C:\Python27\libs\python27.lib

```

在Linux下編譯命令爲

```
gcc main.c great_module.c -o main -I/usr/include/python2.7/ -lpython2.7

```

這個例子中咱們使用了Python的動態類型特性。若是你想指定類型,能夠利用Cython的靜態類型關鍵字。例子以下:

```
#great_module.pyx
cdef public char great_function(const char * a,int index):
return a[index]
```

cython編譯後獲得的.h裏,great_function的聲明是這樣的:

```
__PYX_EXTERN_C DL_IMPORT(char) great_function(char const *, int);
```

很開心對不對!
這樣的話,咱們的main函數已經幾乎看不到Python的痕跡了:

```
//main.c
#include <Python.h>
#include "great_module.h"

int main(int argc, char *argv[]) {
Py_Initialize();
initgreat_module();
printf("%c",great_function("Hello",2));
Py_Finalize();
}
```

在這一部分的最後咱們給一個看似實用的應用(僅限於Windows):
仍是利用剛纔的great_module.pyx,準備一個dllmain.c:

```
#include <Python.h>
#include <Windows.h>
#include "great_module.h"

extern __declspec(dllexport) int __stdcall _great_function(const char * a, int b) {
return great_function(a,b);
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpReserved) {
switch( fdwReason ) {
case DLL_PROCESS_ATTACH:
Py_Initialize();
initgreat_module();
break;
case DLL_PROCESS_DETACH:
Py_Finalize();
break;
}
return TRUE;
}
```

在Visual Studio命令提示符下編譯:

```
cl /LD dllmain.c great_module.c -IC:\Python27\include C:\Python27\libs\python27.lib

```

會獲得一個dllmain.dll。咱們在Excel裏面使用它,沒錯,傳說中的**Excel與Python混合編程**:

<noscript><img data-rawheight="797" data-rawwidth="1007" src="https://pic2.zhimg.com/50/2f45c9f2f8407d46f51f203efc2e8181_hd.jpg" class="origin_image zh-lightbox-thumb" width="1007" data-original="https://pic2.zhimg.com/2f45c9f2f8407d46f51f203efc2e8181_r.jpg"/></noscript>

![](http://upload-images.jianshu.io/upload_images/12778909-433d2ab7e4a6af72.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

參考資料:Cython的官方文檔,質量很是高:
[Welcome to Cython’s Documentation](https://link.zhihu.com/?target=http%3A//docs.cython.org/index.html)

**4 Python調用C/C++(使用SWIG)**

用C/C++對腳本語言的功能擴展是很是常見的事情,Python也不例外。除了SWIG,市面上還有若干用於Python擴展的工具包,比較知名的還有Boost.Python、SIP等,此外,Cython因爲能夠直接集成C/C++代碼,並方便的生成Python模塊,故也能夠完成擴展Python的任務。

答主在這裏選用SWIG的一個重要緣由是,它不只能夠用於Python,也能夠用於其餘語言。現在SWIG已經支持C/C++的好基友Java,主流腳本語言Python、Perl、Ruby、PHP、JavaScript、tcl、Lua,還有Go、C#,以及R。SWIG是基於配置的,也就是說,原則上一套配置改變不一樣的編譯方法就能適用各類語言(固然,這是理想狀況了……)

SWIG的安裝方便,有Windows的預編譯包,解壓即用,綠色健康。主流Linux一般集成swig的包,也能夠下載源代碼本身編譯,SWIG很是小巧,一般安裝不會出什麼問題。

用SWIG擴展Python,你須要有一個待擴展的C/C++庫。這個庫有多是你本身寫的,也有多是某個項目提供的。這裏舉一個不浮誇的例子:但願在Python中用到SSE4指令集的CRC32指令。

首先打開指令集的文檔:[https://software.intel.com/en-us/node/514245](https://link.zhihu.com/?target=https%3A//software.intel.com/en-us/node/514245)
能夠看到有6個函數。分析6個函數的原型,其參數和返回值都是簡單的整數。因而書寫SWIG的配置文件(爲了簡化起見,未包含2個64位函數):

```
/* File: mymodule.i */
%module mymodule

%{
#include "nmmintrin.h"
%}

int _mm_popcnt_u32(unsigned int v);
unsigned int _mm_crc32_u8 (unsigned int crc, unsigned char v);
unsigned int _mm_crc32_u16(unsigned int crc, unsigned short v);
unsigned int _mm_crc32_u32(unsigned int crc, unsigned int v);

```

接下來使用SWIG將這個配置文件編譯爲所謂Python Module Wrapper

```
swig -python mymodule.i

```

獲得一個 mymodule_wrap.c和一個mymodule.py。把它編譯爲Python擴展:

Windows:

```
cl /LD mymodule_wrap.c /o _mymodule.pyd -IC:\Python27\include C:\Python27\libs\python27.lib

```

Linux:

```
gcc -fPIC -shared mymodule_wrap.c -o _mymodule.so -I/usr/include/python2.7/ -lpython2.7
```

注意輸出文件名前面要加一個下劃線。
如今能夠當即在Python下使用這個module了:

```
>>> import mymodule
>>> mymodule._mm_popcnt_u32(10)
2
```

回顧這個配置文件分爲3個部分:

1. 定義module名稱mymodule,一般,module名稱要和文件名保持一致。
2. %{ %} 包裹的部分是C語言的代碼,這段代碼會原封不動的複製到mymodule_wrap.c
3. 欲導出的函數簽名列表。直接從頭文件裏複製過來便可。

還記得本文第2節的那個great_function嗎?有了SWIG,事情就會變得如此簡單:

```
/* great_module.i */
%module great_module
%{
int great_function(int a) {
return a + 1;
}
%}
int great_function(int a);

```

換句話說,SWIG自動完成了諸如Python類型轉換、module初始化、導出代碼表生成的諸多工做。

對於C++,SWIG也能夠應對。例如如下代碼有C++類的定義:

```
//great_class.h
#ifndef GREAT_CLASS
#define GREAT_CLASS
class Great {
private:
int s;
public:
void setWall (int _s) {s = _s;};
int getWall () {return s;};
};
#endif // GREAT_CLASS

```

對應的SWIG配置文件

```
/* great_class.i */
%module great_class
%{
#include "great_class.h"
%}
%include "great_class.h"
```

這裏再也不從新敲一遍class的定義了,直接使用SWIG的%include指令

SWIG編譯時要加-c++這個選項,生成的擴展名爲cxx

```
swig -c++ -python great_class.i
```

Windows下編譯:

```
cl /LD great_class_wrap.cxx /o _great_class.pyd -IC:\Python27\include C:\Python27\libs\python27.lib

```

Linux,使用C++的編譯器

```
g++ -fPIC -shared great_class_wrap.cxx -o _great_class.so -I/usr/include/python2.7/ -lpython2.7
```

在Python交互模式下測試:

```
>>> import great_class
>>> c = great_class.Great()
>>> c.setWall(5)
>>> c.getWall()
5
```

也就是說C++的class會直接映射到Python class

SWIG很是強大,對於Python接口而言,簡單類型,甚至指針,都無需人工干涉便可自動轉換,而複雜類型,尤爲是自定義類型,SWIG提供了typemap供轉換。而一旦使用了typemap,配置文件將再也不在各個語言當中通用。

**參考資料:**
SWIG的官方文檔,質量比較高。[SWIG Users Manual](https://link.zhihu.com/?target=http%3A//www.swig.org/Doc3.0/Contents.html%23Contents)
有個對應的中文版官網,不少年沒有更新了。

**寫在最後:**
因爲CPython自身的結構設計合理,使得Python的C/C++擴展很是容易。若是打算快速完成任務,Cython(C/C++調用Python)和SWIG(Python調用C/C++)是很不錯的選擇。可是,一旦涉及到比較複雜的轉換任務,不管是繼續使用Cython仍是SWIG,仍然須要學習Python源代碼。

本文使用的開發環境:Python 2.7.10Cython 0.22SWIG 3.0.6Windows 10 x64 RTMCentOS 7.1 AMD 64Mac OSX 10.10.4文中所述原理與具體環境適用性強。文章所述代碼均用於演示,缺少必備的異常檢查

相關文章
相關標籤/搜索