Linux 動態庫 so 使用

來源:互聯網
上載者:User

折騰了會 dll 覺得不爽,改玩 so 去:

一.  編寫個C檔案:test.c

#include<stdio.h>// file test.cint say(){    printf("Hello, Linux so\n");    return 0;}int add(int x, int y){    return x+y;}

二. 編譯成動態庫 .so :

 ~ # gcc -shared -o test.so test.c/usr/lib/gcc/x86_64-pc-linux-gnu/4.5.3/../../../../x86_64-pc-linux-gnu/bin/ld: /tmp/cc3GkPar.o: relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC/tmp/cc3GkPar.o: could not read symbols: Bad valuecollect2: ld returned 1 exit status

出錯了,說是要加個 -fPIC 參數(編譯成位置無關代碼,不然你的程式在別的地方肯可能運行不了):

~ # gcc -fPIC -shared -o test.so test.c

OK,成功!

三.  C語言中使用使用該動態庫(test.so)

1. 編寫C file

#include<stdio.h>// file: myso.cint main(){    say();    printf("%d\n",add(3+4));    return 0;}

2. 編譯

~ # gcc -o myso myso.c /root/test.so

3. 運行

~ # ./mysoHello, Linux so1697202183

結果明顯不正確,3+4 怎麼會是 1697201283 ?  原來,add(3+4) 參數傳錯了 !!

四. Python中使用

1. 編寫Python 檔案

#!/usr/bin/pythonfrom ctypes import *myso = cdll.LoadLibrary('/root/test.so')myso.say()add = myso.addadd.argtypes = [c_int, c_int]    #傳入參數類型add.restype = c_int              #傳回值類型print add(2,3)

2. 使用

 ~ # python myso.pyHello, Linux so...5

五.

相關文章

聯繫我們

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