現在的位置: 首頁 > 編程語言 > 正文

[原]用C擴展python

2018年08月29日 編程語言 ⁄ 共 892字 ⁄ 字型大小 評論關閉
備了個忘

1.創建應用程序代碼
2.利用樣板來包裝代碼
    1.包含
Python 的頭文件。 
     
  #include "Python.h" //需將python安裝目錄下的include文件夾包含進工程
    2.為每個模塊的每一個函數增加一個型如
PyObject* Module_func()的包裝函數。
    包裝函數格式:
static PyObject *Extest_fac(PyObject *self, PyObject
*args)
{
int res; //parse result
int num; //arg for fac()
PyObject *retval;
res = PyArg_ParseTuple(args, "i",
&num);//轉換從python傳入的參數為整數
if(!res)//type error
{
return NULL;
}
res = fac(num);//函數調用
retval = (PyObject *)Py_BuildValue("i",
res);//將res從c的int類型轉換為python對象類型
return retval;
}      
  
    3.為每個模塊增加一個型如
PyMethodDef ModuleMethods[]的數組。 
     
  static PyMethodDef
ExtestMethods[] = {
{"fac", Extest_fac, METH_VARARGS},
{"doppel", Extest_doppel, METH_VARARGS},
{NULL, NULL},
};
    4.增加模塊初始化函數 void
initModule() 
void initExtest()
{
Py_InitModule("Extest", ExtestMethods);
}
3.編譯與測試
    1.新建setup.py
from distutils.core import setup, Extension
MOD = 'Extest'
setup(name = MOD, ext_modules = [Extension(MOD, sources =
['Extest.c'])])
    2.python setup.py build
--compiler=mingw32

抱歉!評論已關閉.