python 調(diào)用c語言函數(shù)的方法
雖然python是萬能的,但是對于某些特殊功能,需要c語言才能完成。這樣,就需要用python來調(diào)用c的代碼了
具體流程:
c編寫相關(guān)函數(shù) ,編譯成庫
然后在python中加載這些庫,指定調(diào)用函數(shù)。
這些函數(shù)可以char ,int, float, 還能返回指針。
以下示例:
通過python調(diào)用c函數(shù),返回"hello,world 字符串"
新建c語言文件 hello.c
touch hello.c
#include <stdio.h>
char *get_str()
{
return "hello,world"
}
編譯成庫
gcc -o hello.so --share -fPIC hello.c
新建python腳本
touch test.py
from ctypes import *
dll = CDLL("./hello.so")
dll.get_str.restype = c_char_p
str = dll.get_str()
print(string_at(str, 11))
執(zhí)行python腳本
[feng@arch python_c]$ python test.py hello,world
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解django+django-celery+celery的整合實戰(zhàn)
這篇文章主要介紹了詳解django+django-celery+celery的整合實戰(zhàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03

