Python調用C語言開發(fā)的共享庫方法實例
更新時間:2015年03月18日 11:24:28 投稿:junjie
這篇文章主要介紹了Python調用C語言開發(fā)的共享庫方法實例,本文同時給出了C語言和Python調用簡單實例,需要的朋友可以參考下
在helloworld工程中,編寫了一個簡單的兩個數(shù)值相加的程序,編譯成為共享庫后,如何使用python對其進行調用呢?
使用ll命令列出當前目錄下的共享庫,其中共享庫名為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*
進入python的命令行模式進行C語言實現(xiàn)的兩個數(shù)值相加的程序的調用;
復制代碼 代碼如下:
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類(此類即是調用C語言動態(tài)庫的方法)
復制代碼 代碼如下:
>>> import ctypes
打開當前目錄的動態(tài)庫
復制代碼 代碼如下:
>>> lib=ctypes.cdll.LoadLibrary("./libhelloworld.so.0.0.0")
調用動態(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
相關文章
Django的restframework接口框架自定義返回數(shù)據格式的示例詳解
這篇文章主要介紹了Django的restframework接口框架自定義返回數(shù)據格式,本文介紹了通過Django的restframework接口框架自定義Response返回對象來自定義返回數(shù)據格式,本文通過示例代碼給大家介紹的非常詳細,需要的朋友可以參考下2022-07-07解決更新tensorflow后應用tensorboard報錯的問題
這篇文章主要介紹了解決更新tensorflow后應用tensorboard報錯的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03使用pyinstaller打包django的方法實現(xiàn)
本文主要介紹了使用pyinstaller打包django的方法,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09