Linux下动态库so的生成与使用
标签:
linux动态库so生成使用杂谈 |
一.
[cpp] view
plaincopyprint?
-
#include<stdio.h>
-
//
file test.c -
int
say() -
{
-
printf("Hello, Linux );so\n" -
return 0; -
}
-
-
int
add( intx, inty) -
{
-
return x+y; -
}
二. 编译成动态库 .so :
[plain] view
plaincopyprint?
-
~ # 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 参数(编译成位置无关代码,不然你的程序在别的地方肯可能运行不了):
[plain] view
plaincopyprint?
-
~
# gcc -fPIC -shared -o test.so test.c
OK,成功!
三.
1. 编写C file
[cpp] view
plaincopyprint?
-
#include<stdio.h>
-
//
file: myso.c -
int
main() -
{
-
say(); -
printf("%d\n",add(3+4)); -
return 0; -
}
2. 编译
[plain] view
plaincopyprint?
-
~
# gcc -o myso myso.c /root/test.so
3. 运行
[plain] view
plaincopyprint?
-
~
# ./myso -
Hello,
Linux so -
1697202183
结果明显不正确,3+4 怎么会是 1697201283 ?
四. Python中使用
1. 编写Python 文件
[python] view
plaincopyprint?
-
#!/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] view
plaincopyprint?
-
~ #python myso.py -
Hello,
Linux so... -
5

加载中…