雖然python是萬能的,但是對於某些特殊功能,需要c語言才能完成。這樣,就需要用python來調用c的代碼了
具體流程:
c編寫相關函數 ,編譯成庫
然后在python中加載這些庫,指定調用函數。
這些函數可以char ,int, float, 還能返回指針。
以下示例:
通過python調用c函數,返回"hello,world 字符串"
新建c語言文件 hello.c
touch hello.c
1 #include <stdio.h> 2 3 char *get_str() 4 { 5 return "hello,world" 6 }
編譯成庫
gcc -o hello.so --share -fPIC hello.c
新建python文件
touch test.py
1 from ctypes import * 2 3 dll = CDLL("./hello.so") 4 dll.get_str.restype = c_char_p 5 str = dll.get_str() 6 print(string_at(str, 11))
# 直接調用
執行python文件
1 [feng@arch python_c]$ python test.py 2 hello,world
這就是python調用c的簡單案例實現