Python調(diào)用C語言開發(fā)的共享庫方法實例
在helloworld工程中,編寫了一個簡單的兩個數(shù)值相加的程序,編譯成為共享庫后,如何使用python對其進(jìn)行調(diào)用呢?
使用ll命令列出當(dāng)前目錄下的共享庫,其中共享庫名為libhelloworld.so.0.0.0
ufo@ufo:~/helloworld/.libs$ ll
總用量 32
drwxr-xr-x 2 ufo ufo 4096 1月 29 14:54 ./
drwxr-xr-x 6 ufo ufo 4096 1月 29 16:08 ../
-rw-r--r-- 1 ufo ufo 3816 1月 29 14:54 helloworld.o
-rw-r--r-- 1 ufo ufo 3956 1月 29 14:54 libhelloworld.a
lrwxrwxrwx 1 ufo ufo 19 1月 29 14:54 libhelloworld.la -> ../libhelloworld.la
-rw-r--r-- 1 ufo ufo 983 1月 29 14:54 libhelloworld.lai
lrwxrwxrwx 1 ufo ufo 22 1月 29 14:54 libhelloworld.so -> libhelloworld.so.0.0.0*
lrwxrwxrwx 1 ufo ufo 22 1月 29 14:54 libhelloworld.so.0 -> libhelloworld.so.0.0.0*
-rwxr-xr-x 1 ufo ufo 9038 1月 29 14:54 libhelloworld.so.0.0.0*
進(jìn)入python的命令行模式進(jìn)行C語言實現(xiàn)的兩個數(shù)值相加的程序的調(diào)用;
ufo@ufo:~/helloworld/.libs$ python
Python 2.7.4 (default, Sep 26 2013, 03:20:56)
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
載入ctypes類(此類即是調(diào)用C語言動態(tài)庫的方法)
>>> import ctypes
打開當(dāng)前目錄的動態(tài)庫
>>> lib=ctypes.cdll.LoadLibrary("./libhelloworld.so.0.0.0")
調(diào)用動態(tài)庫中的接口
>>> lib.add(5,7)
12
兩個參數(shù)的相加的函數(shù)如下:
ufo@ufo:~/helloworld$ cat helloworld.c
#include <stdio.h>
#include <stdlib.h>
int add(int a, int b)
{
int c = a + b;
return c;
}
編譯動態(tài)庫的命令行:
gcc -shared -fPIC -DPIC helloworld.c -o libhelloworld.so.0.0.0
相關(guān)文章
使用Python中OpenCV和深度學(xué)習(xí)進(jìn)行全面嵌套邊緣檢測
這篇文章主要介紹了使用Python中OpenCV和深度學(xué)習(xí)進(jìn)行全面嵌套邊緣檢測,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05
僅用500行Python代碼實現(xiàn)一個英文解析器的教程
這篇文章主要介紹了僅用500行Python代碼實現(xiàn)一個英文解析器的教程,自然語言處理近來也是業(yè)界中一個熱門課題,作者為NLP方向的開發(fā)者,需要的朋友可以參考下2015-04-04
python3實現(xiàn)小球轉(zhuǎn)動抽獎小游戲
這篇文章主要為大家詳細(xì)介紹了python3實現(xiàn)小球轉(zhuǎn)動抽獎小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-05-05
用實例分析Python中method的參數(shù)傳遞過程
這篇文章主要介紹了用實例分析Python中method的參數(shù)傳遞過程,包括instancemethod和staticmethod等實例,需要的朋友可以參考下2015-04-04
使用pyinstaller打包.exe文件的詳細(xì)教程
PyInstaller是一個跨平臺的Python應(yīng)用打包工具,能夠把 Python 腳本及其所在的 Python 解釋器打包成可執(zhí)行文件,下面這篇文章主要給大家介紹了關(guān)于使用pyinstaller打包.exe文件的相關(guān)資料,需要的朋友可以參考下2022-04-04

