折騰了會 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
五.