折腾了会 dll 觉得不爽,改玩 so 去:
一. 编写个C文件:test.c
#include<stdio.h> // file test.c int 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 value collect2: 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.c int main() { say(); printf("%d\n",add(3+4)); return 0; }
2. 编译
~ # gcc -o myso myso.c /root/test.so
3. 运行
~ # ./myso Hello, Linux so 1697202183
结果明显不正确,3+4 怎么会是 1697201283 ? 原来,add(3+4) 参数传错了 !!
四. Python中使用
1. 编写Python 文件
#!/usr/bin/python from ctypes import * myso = cdll.LoadLibrary('/root/test.so') myso.say() add = myso.add add.argtypes = [c_int, c_int] #传入参数类型 add.restype = c_int #返回值类型 print add(2,3)
2. 使用
~ # python myso.py Hello, Linux so... 5
五.