python调用c代码
Linux環境下使用python調用C的printf例子:
#!/usr/bin/env python2.7 #-*- coding:utf-8 -*- from ctypes import * def test():#libc = cdll.LoadLibrary("libc.so.6")libc = CDLL("libc.so.6")msg = "hello world!\n"libc.printf("Testing:%s",msg) def main():test()if __name__ == '__main__':main()
python中結構體對應的類型:
#!/usr/bin/env python2.7 #-*- coding:utf-8 -*- from ctypes import * class barley_amout(Structure):_fields_ = [("barley_long",c_long),("barley_int",c_int),("barley_char",c_char*100)] def main():bu = barley_amout(66,44,"Hello world")print bu.barley_longprint bu.barley_intprint bu.barley_charif __name__ == '__main__':main()?
python中Union體對應的類型:
class _U(Union):_fields_ = [("lptdesc", POINTER(TYPEDESC)),("lpadesc", POINTER(ARRAYDESC)),("hreftype", HREFTYPE)]class TYPEDESC(Structure):_anonymous_ = ("u",)_fields_ = [("u", _U),("vt", VARTYPE)]調用方式
td = TYPEDESC() td.vt = VT_PTR td.lptdesc = POINTER(some_type) td.u.lptdesc = POINTER(some_type)?
生成單個so動態庫并通過python調用
1、test.c文件
#include <stdio.h>void print_helloworld(){printf("%s","Hello world!\n"); }int main(){print_helloworld();return 0; }2、生成動態庫文件
gcc -fPIC -c test.c -o libtest.o通過這種方式在python調用的時候出現
OSError: ./libtest.o: only ET_DYN and ET_EXEC can be loaded
參照這個博客http://xieruilin.iteye.com/blog/730422
修改方式如下:
gcc -fpic -shared -o libtest.o ./test.c3、python調用
[root@typhoeus79 20140509]# more call_test.py #!/usr/bin/env python2.7 #-*- coding:utf-8 -*-from ctypes import * def test():libc = CDLL("./libtest.o")libc.print_helloworld()if __name__ == '__main__':test() [root@typhoeus79 20140509]# ./call_test.py Hello world!?
?參考文獻
https://docs.python.org/2/library/ctypes.html?highlight=structure#ctypes.Structure
https://docs.python.org/2.7/library/ctypes.html#module-ctypes
http://chimera.labs.oreilly.com/books/1230000000393/ch15.html#_solution_240
http://wangrqa.blog.163.com/blog/static/170946827201010309510247/
http://csl.name/C-functions-from-Python/
http://mypyg.iteye.com/blog/845915
轉載于:https://www.cnblogs.com/gsblog/p/3718982.html
總結
以上是生活随笔為你收集整理的python调用c代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android中fragment之间和A
- 下一篇: jump大乱斗键位设置