linux 下的動態庫製作 以及在python 中如何調用 c 函數庫

來源:互聯網
上載者:User

標籤:linux 動態庫 python

linux 下的動態庫製作 以及在python 中如何調用 c 函數庫

  1. 動態庫:

    動態庫又稱動態連結程式庫英文為DLL,是Dynamic Link Library 的縮寫形式,DLL是一個包含可由多個程式同時使用的代碼和資料的庫,DLL不是可執行檔。動態連結提供了一種方法,使進程可以調用不屬於其可執行代碼的函數。函數的可執行代碼位於一個 DLL 中,該 DLL 包含一個或多個已被編譯、連結並與使用它們的進程分開儲存的函數。DLL 還有助於共用資料和資源。多個應用程式可同時訪問記憶體中單個DLL 副本的內容。DLL 是一個包含可由多個程式同時使用的代碼和資料的庫。Windows下動態庫為.dll尾碼,在linux在為.so尾碼。

  2. 動態庫製作:

     gcc -fPIC -g -c -Wall a.c

 gcc -fPIC -g -c -Wall b.c

 gcc -shared -Wl,-soname,liblusterstuff.so.1 -o liblusterstuff.so.1.0.1 a.o b.o -lc

注:  可以簡寫為:   gcc -fPIC -O2 -shared mydll.c -o  mydll.so

3. python 中如何調用 c 語言產生的動態庫:

(1) : 先產生一個動態庫 : 如

    gcc  - fPIC -O2  -shared  print_lib.c   -o   print_lib.so

    ===================================================

      struct  stu

        {        

            int num;

            char name [30] ;

            float  score ;

        }

        void print0 ( int a )

         {

                      printf (" %d\n" , a );

        }

        void print 2 ( struct data)

        {

                        printf ("%d \n", data. num);

                        printf (" %s\n", data .name);

                        printf (" %f\n", data. score);

        }

        void print 3 ( struct * p)

        {

                        print (" %d\n", p->num);

                        print ("%s\n", p->name);

                        print ("%f\n", p->float);

        }

====================================================

(2): python 定一個傳給動態庫 的 資料類型

     from ctypes import *

    class py_st (Strutcture):

                _fields =

                [    ( "num", c_int), ("name", string) , ("score", c_float) ]

(3) python 使用動態庫:

    1.    // 載入動態庫

    fileName  = "home/ zyh / tmp / print_dll.so "

    lib = cdll . loadLibrary ( fileName)

    2.    // 定義變數

    param = py_st ( )

    3.   // 給結構體賦值

    param . num = 1001

    param . name =  "hello word"

    param . score = 95.5

    

    lib. print 0 ( 10)

    lib . print 1 ( param)

    lib . print 2 ( pointer (param) )

  


本文出自 “12690807” 部落格,轉載請與作者聯絡!

linux 下的動態庫製作 以及在python 中如何調用 c 函數庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.