分類: c/c++
程式設計技巧
programes
2008-04-23 09:31
1232人閱讀收藏
舉報python
擴充套件語言
cmethods
null
這裡檢視關於用c語言擴充套件python的功能
。只要安裝了python,在用c進行python的擴充套件程式設計時不需要額外安裝任何東西,python會將標頭檔案防置於/usr/include/python下,根據不同的版本稍有不同。
下面給出乙個例程,它將產生乙個可以被python匯入的模組,名為example,其中包含乙個splitwords的函式,這個函式接受兩個引數,第乙個是包含單詞的字串,第二個是單詞的分隔符,這也是乙個字串,其中的每個字元都會用來作為分割單詞的字元。為方便起見,所有的函式都放置於乙個檔案example.c中。
// filename example.c
#include
return list;}
pyobject* wrap_splitwords(pyobject *self, pyobject *args)
static pymethoddef methods = ,
};
void initexample()
這裡產生的python物件返回給python,所以就不需要考慮引用計數的問題了。splitwords為c語言的擴充套件函式,用wrap_splitwords封裝,example中的方法列表由methods給出,初始化函式為initexample,只要看過上面的參考鏈結,這些都不需再解釋。
由於我的python版本是2.4.4,它的頭檔案目錄位於/usr/include/python2.4下。使用gcc來編譯,不要使用g++,以這個example為例,由gcc產生的so中可以找到'initexample'符號,而g++產生的為'_z15initexamplev',python在import時會出現找不到初始化函式的錯誤:
importerror: dynamic module does not define init function (initexample)
如果一定要使用g++,或許可以將c++的擴充套件程式單獨放到乙個檔案,從中產生乙個靜態庫檔案,而封裝的程式仍使用gcc。這個設想還沒有試驗過,下面僅使用gcc:
gcc -fpic -c -i/usr/include/python2.4 -i/usr/lib/python2.4/config example.c
gcc -shared -o example.so example.o
只要example.so可以被找到(在python執行的當前目錄,或者是在/usr/lib下,或者由ld_library_path指定)python就可以直接import:
>>> import example
>>> s = 'ab,cde:ghij klmno'
>>> example.splitwords(s, ' ')
['ab,cde:ghij', 'klmno']
>>> example.splitwords(s, ' :')
['ab,cde', 'ghij', 'klmno']
>>> example.splitwords(s, ' :,')
['ab', 'cde', 'ghij', 'klmno']
C語言擴充套件Python
python具有很好的開發靈活性,最大的特點是c語言可以對python進行擴充套件,目前工作中正在進行相關的開發,第一篇文章作為基礎.實現c函式,用python api封裝,實現倆個功能,1.say hello,列印hello world 2.calc pv,做加法用算.以下為使用方法 01pyth...
用C語言寫PHP擴充套件
1 預定義 在home目錄,也可以其他任意目錄,寫乙個檔案,例如caleng module.def 內容是你希望定義的函式名以及引數 int a int x,int y string b string str,int n 2 到php原始碼目錄的ext目錄 cd usr local php 5.4....
用C語言寫PHP擴充套件
用c語言寫php擴充套件 1 預定義 在home目錄,也可以其他任意目錄,寫乙個檔案,例如caleng module.def 內容是你希望定義的函式名以及引數 int a int x,int y string b string str,int n 2 到php原始碼目錄的ext目錄 cd usr l...