Python調用C語言開發的共用庫方法執行個體_python

來源:互聯網
上載者:User

在helloworld工程中,編寫了一個簡單的兩個數值相加的程式,編譯成為共用庫後,如何使用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語言實現的兩個數值相加的程式的調用;
複製代碼 代碼如下:

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語言動態庫的方法)
複製代碼 代碼如下:

>>> import ctypes

開啟目前的目錄的動態庫
複製代碼 代碼如下:

>>> lib=ctypes.cdll.LoadLibrary("./libhelloworld.so.0.0.0")

調用動態庫中的介面
複製代碼 代碼如下:

>>> lib.add(5,7)
12

兩個參數的相加的函數如下:
複製代碼 代碼如下:

ufo@ufo:~/helloworld$ cat helloworld.c
#include <stdio.h>
#include <stdlib.h>

int add(int a, int b)
{
    int c = a + b;
    return c;
}


編譯動態庫的命令列:
複製代碼 代碼如下:

gcc -shared -fPIC -DPIC helloworld.c -o libhelloworld.so.0.0.0

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.