一. 编写个C文件:test.c
1. #include<stdio.h>
2. // file test.c
3. int say()
4. {
5. printf("Hello, Linux so\n");
6. return 0;
7. }
8.
9. int add(int x, int y)
10. {
11. return x+y;
12. }
二. 编译成动态库 .so :
1. ~ # gcc -shared -o test.so test.c
2. /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
3. /tmp/cc3GkPar.o: could not read symbols: Bad value
4. collect2: ld returned 1 exit status
出错了,说是要加个 -fPIC 参数(编译成位置无关代码,不然你的程序在别的地方肯可能运行不了):
1. ~ # gcc -fPIC -shared -o test.so test.c
OK,成功!
三. C语言中使用使用该动态库(test.so)
1. 编写C file
1. #include<stdio.h>
2. // file: myso.c
3. int main()
4. {
5. say();
6. printf("%d\n",add(3+4));
7. return 0;
8. }
2. 编译
1. ~ # gcc -o myso myso.c /root/test.so
3. 运行
1. ~ # ./myso
2. Hello, Linux so
3. 1697202183
结果明显不正确,3+4 怎么会是 1697201283 ? 原来,add(3+4) 参数传错了 !!
四. Python中使用
1. 编写Python 文件
1. #!/usr/bin/python
2. from ctypes import *
3.
4. myso = cdll.LoadLibrary('/root/test.so')
5.
6. myso.say()
7.
8. add = myso.add
9. add.argtypes = [c_int, c_int] #传入参数类型
10. add.restype = c_int #返回值类型
11.
12. print add(2,3)
2. 使用
1. ~ # python myso.py
2. Hello, Linux so...
3.
4. 5
http://blog.sina.com.cn/s/blog_7769660f01011pf1.html