Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 C/C++ 擴展 Python 的四種路徑:ctypes、Boost、SWIG 與 SIP

用 Python 寫應用確實快,但有時基於效能或既有資產的考量,需要把 C/C++ 的程式碼接回 Python(例如替自家產品補上一層 Python 介面)。這件事我拖了很久,今天終於坐下來一次做完,順手記錄成篇。

測試環境:CentOS 6.5 x64,Python 2.6。

方案一:直接呼叫動態庫(ctypes)

1. 撰寫動態庫原始碼

以「取最大值」為例,檔案 callTest1.cpp:

extern "C"
{
    int Max(int i1,int i2)
    {
        return (i1>i2)?i1:i2;
    }
}

用 extern "C" 是為了關閉 C++ 的 name mangling,讓符號名稱保持為 Max,否則 Python 端找不到函式。接著編譯:

g++ -fPIC -shared -o libcallTest1.so callTest1.cpp

2. 在 Python 中載入

#! /usr/bin/env python

from ctypes import *
import os

so1 = CDLL(os.getcwd() + '/libcallTest1.so')
print so1.Max(1,3)

ctypes 的優點是零依賴,缺點是只能處理 C 介面,C++ 類別要自己包一層。

方案二:Boost.Python

這種方式能直接產出 Python 模組,import 就能用。前提是先裝好 boost 庫,官網:https://www.boost.org/

模組程式碼 boostCallTest1.cpp:

int Max(int i1,int i2)
{
    return (i1>i2)?i1:i2;
}

#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
using namespace boost::python;

BOOST_PYTHON_MODULE(boostCallTest1)
{
    def("Max",Max);
}

編譯腳本 setup.py:

#!/usr/bin/env python

from distutils.core import setup
from distutils.extension import Extension

setup(name="PackageName",
    ext_modules=[
    Extension("boostCallTest1", ["boostCallTest1.cpp"],
    libraries = ["boost_python"])
])

編譯並測試:

python setup.py build

產物在 build 目錄下的 boostCallTest1.so,進入該目錄即可使用:

>>> import boostCallTest1
>>> boostCallTest1.Max(1,3)
3

方案三:SWIG

SWIG 是一套把 C/C++ 撰寫的軟體與各種高階語言做嵌入連結的開發工具,支援 Perl、PHP、Python、Tcl、Ruby 等。官網:https://www.swig.org/download.html,也可直接 yum install swig。

程式碼 swigCall.cpp:

int Max(int i1,int i2)
{
    return (i1>i2)?i1:i2;
}

介面檔 swigCall.i:

%module swigCall
%{
extern int Max(int i1,int i2);
%}

extern int Max(int i1,int i2);

Makefile:

all:
    make swigCall

swigCall:
    swig -python -c++ swigCall.i
    g++ -c swigCall.cpp swigCall_wrap.cxx -I/usr/include/python2.6/ -fPIC
    g++ -shared swigCall.o swigCall_wrap.o -o _swigCall.so

clean:
    rm -f swigCall_wrap.c*
    rm -f *.py*
    rm -f *.so
    rm -f *.o

要留意:處理 C++ 原始碼時,swig 指令務必帶上 -c++ 參數。

方案四:SIP

SIP 由 SWIG 演進而來,專門服務於 Python 呼叫 C/C++ 模組的場景。提醒一句,這裡的 SIP 與 VoIP 協定裡的 SIP 完全無關,別搞混。使用前需安裝 Python 的 sip 庫。

1.1 標頭檔 sipCall.h

class TestMode
{
public:
    int Max(int i1,int i2);
};

1.2 實作 sipCall.cpp

#include "sipCall.h"

int TestMode::Max(int i1,int i2)
{
    return (i1>i2)?i1:i2;
}

2. 介面檔 sipCall.sip

%Module TestMode

class TestMode {
%TypeHeaderCode
#include "sipCall.h"
%End

public:
    int Max(int i1,int i2);
};

3. 產生靜態庫 genlib.sh

#! /bin/bash
g++ -c -fPIC sipCall.cpp
ar -crs libsipCall.a sipCall.o

4. 撰寫 configure 腳本(用來產生 Makefile)

#! /usr/bin/env python

import os
import sipconfig

build_file = "sipCall.sbf"
config = sipconfig.Configuration()
cmd = " ".join([config.sip_bin, "-c", ".", "-b", build_file, "sipCall.sip"])
os.system(cmd)

makefile = sipconfig.SIPModuleMakefile(config, build_file)
makefile.extra_libs = ["sipCall"]
makefile.LIBDIR.append(".")
makefile.generate()

5. 依序執行

先跑 genlib.sh 產生 lib 檔,再跑 configure.py 產生 Makefile,最後 make 產出 so 模組。

6. 驗證

>>> import TestMode
>>> dir(TestMode)
['TestMode', '__doc__', '__file__', '__name__', '__package__']
>>> s = TestMode.TestMode()
>>> s.Max(1,3)
3

四種方案沒有絕對優劣:ctypes 最輕、Boost.Python 型別轉換最自然、SWIG 支援語言最廣、SIP 則與 Qt/PyQt 生態最合拍。挑選時看的是既有程式碼風格與團隊熟悉度。

延伸閱讀:

Python:在指定目錄下查找滿足條件的檔案 https://www.linuxidc.com/Linux/2015-08/121283.htm

Python2.7.7 源碼分析 https://www.linuxidc.com/Linux/2015-08/121168.htm

CentOS 上源碼安裝 Python3.4 https://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》高清 PDF 中文版 https://www.linuxidc.com/Linux/2013-06/85425.htm

Python 腳本獲取 Linux 系統資訊 https://www.linuxidc.com/Linux/2013-08/88531.htm

Copyright © Linux教程網 All Rights Reserved