Python 和 C 在我看來簡直是無敵組合:一般業務邏輯用 Python 快速開發原型,遇到 Python 執行效率不佳的環節,就交給 C 編譯好的連結庫來加速。
在 Python 3.2 中,可以透過 ctypes 模組純粹地存取 C 連結庫,也可以走傳統的 C API 方式。ctypes 固然方便,但若需要「回調」(由 C 反向呼叫 Python),就仍得採用傳統方式。以下整理一份 3.2.2 的簡單範例。
依官方命名慣例,檔名前段是模組名,後段是 module.c。注意 Python 3 的初始化函式命名規則已改為 PyInit_模組名:
#include <Python.h> // 必須先 include Python.h,它包含了一些預編譯宏與 stdlib.h 等標頭檔
/* 將要被呼叫的函式 */
long func1(long a, long b)
{
return a + b;
}
/* 方法命名慣例是「模組名_方法名」,這裡方法名是 system */
static PyObject *
lzy_system(PyObject *self, PyObject *args)
{
const char *command;
long a, b;
int sts;
if (!PyArg_ParseTuple(args, "ii", &a, &b)) // 讀入兩個整數參數並轉成 C 型別
return NULL;
sts = func1(a, b);
return PyLong_FromLong(sts); // 回傳前需轉成 PyObject 型別
}
/* 定義模組中的方法 */
static PyMethodDef LzyMethods[] =
{
{"func", lzy_system, METH_VARARGS, "my first test function"}, // func 是 Python 中呼叫的名稱
{NULL, NULL, 0, NULL}
};
/* 定義模組 */
static struct PyModuleDef lzymodule =
{
PyModuleDef_HEAD_INIT,
"lzy",
NULL,
-1,
LzyMethods
};
/* 相當於主函式,命名一定要為「PyInit_模組名」 */
PyMODINIT_FUNC PyInit_lzy(void)
{
return PyModule_Create(&lzymodule);
}
gcc lzymodule.c -shared -I /usr/local/include/python3.2m/ -o lzy.so -fPIC
import lzy lzy.func(1, 230)
若不想手動 gcc,也可以用 distutils 腳本:
from distutils.core import setup, Extension
test_mod = Extension('lzy', sources = ['lzymodule.c'])
setup(name = 'lzy',
version = '1.0',
description = 'lzy test extension module',
ext_modules = [test_mod])
然後執行 python setup.py build 與 python setup.py install 即可完成編譯與安裝。