第一步:上C源碼(代碼框架是參考一位網友的^_^!):
/*************************************************************************
> File Name: python_test.c
> Author:
> Mail:
> Created Time: Thu 03 Dec 2015 10:45:04 PM PST
************************************************************************/
#include <python2.7/Python.h> //包含python的頭文件
#include <stdio.h>
/*1 c/cpp中的函數 */
int my_c_function(int j,int i) {
int n = i+j;
printf("i + j = %d\n",n);
return n;
}
// 2 python 包裝
static PyObject * wrap_my_c_fun(PyObject *self, PyObject *args) {
int command;
int n;
int i;
if (!PyArg_ParseTuple(args, "ii",&command,&i))//這句是把python的變量args轉換成c的變量command
return NULL;
n = my_c_function(command,i);//調用c的函數
return Py_BuildValue("i",n);//把c的返回值n轉換成python的對象
}
// 3 方法列表
static PyMethodDef MyCppMethods[] = {
//MyCppFun1是python中註冊的函數名,wrap_my_c_fun是函數指針
{ "MyCppFun1", wrap_my_c_fun, METH_VARARGS, "Execute a shellcommand." },
{ NULL, NULL, 0, NULL }
};
// 4 模塊初始化方法
PyMODINIT_FUNC initMyCppModule(void) {
//初始模塊,把MyCppMethods初始到MyCppModule中
PyObject *m = Py_InitModule("MyCppModule", MyCppMethods);
if (m == NULL)
return;
}
第二步:編寫python 編譯代碼(setup.py)
#!/usr/bin env python
from distutils.core import setup, Extension
MOD = 'MyCppModule'
setup(name=MOD,version = '1.0', ext_modules=[Extension(MOD,sources=['python_test.c'])])
第三步:輸入編譯命令
python setup.py build
輸入命令後會打印如下信息(打印類似信息及成功,否則就去檢查代碼):
kjlr@kjlr-ThinkPad-E450c:~/python_test$ python setup.py build
running build
running build_ext
building 'MyCppModule' extension
x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c python_test.c -o build/temp.linux-x86_64-2.7/python_test.o
x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -D_FORTIFY_SOURCE=2 -g -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/python_test.o -o build/lib.linux-x86_64-2.7/MyCppModule.so
第四步:輸入命令將我們做好的安裝到python中
sudo python setup.py install
輸入命令後會打印如下信息(打印類似信息及成功,否則就去檢查代碼):
kjlr@kjlr-ThinkPad-E450c:~/python_test$ sudo python setup.py install
[sudo] password for kjlr:
running install
running build
running build_ext
running install_lib
copying build/lib.linux-x86_64-2.7/MyCppModule.so -> /usr/local/lib/python2.7/dist-packages
running install_egg_info
Removing /usr/local/lib/python2.7/dist-packages/MyCppModule-1.0.egg-info
Writing /usr/local/lib/python2.7/dist-packages/MyCppModule-1.0.egg-info
第五步:在解釋器裏測試我們做好的包
kjlr@kjlr-ThinkPad-E450c:~$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import MyCppModule
>>> MyCppModule.MyCppFun1(1,3)
i + j = 4
4
>>> MyCppModule.MyCppFun1(1,308)
i + j = 309
309
>>>
第六步:如有興趣深究者可閱讀《python核心編程》第二版
注:本示例一共用到了兩個文件,python_test.c
setup.py,都在同一個目錄下。