您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Python调用C语言开发的共享库方法实例

2025/7/17 18:04:33发布36次查看
在helloworld工程中,编写了一个简单的两个数值相加的程序,编译成为共享库后,如何使用python对其进行调用呢?
使用ll命令列出当前目录下的共享库,其中共享库名为libhelloworld.so.0.0.0
复制代码 代码如下:
ufo@ufo:~/helloworld/.libs$ ll
总用量 32
drwxr-xr-x 2 ufo ufo 4096  1月 29 14:54 ./
drwxr-xr-x 6 ufo ufo 4096  1月 29 16:08 ../
-rw-r--r-- 1 ufo ufo 3816  1月 29 14:54 helloworld.o
-rw-r--r-- 1 ufo ufo 3956  1月 29 14:54 libhelloworld.a
lrwxrwxrwx 1 ufo ufo   19  1月 29 14:54 libhelloworld.la -> ../libhelloworld.la
-rw-r--r-- 1 ufo ufo  983  1月 29 14:54 libhelloworld.lai
lrwxrwxrwx 1 ufo ufo   22  1月 29 14:54 libhelloworld.so -> libhelloworld.so.0.0.0*
lrwxrwxrwx 1 ufo ufo   22  1月 29 14:54 libhelloworld.so.0 -> libhelloworld.so.0.0.0*
-rwxr-xr-x 1 ufo ufo 9038  1月 29 14:54 libhelloworld.so.0.0.0*
进入python的命令行模式进行c语言实现的两个数值相加的程序的调用;
复制代码 代码如下:
ufo@ufo:~/helloworld/.libs$ python
python 2.7.4 (default, sep 26 2013, 03:20:56)
[gcc 4.7.3] on linux2
type help, copyright, credits or license for more information.
载入ctypes类(此类即是调用c语言动态库的方法)
复制代码 代码如下:
>>> import ctypes
打开当前目录的动态库
复制代码 代码如下:
>>> lib=ctypes.cdll.loadlibrary(./libhelloworld.so.0.0.0)
调用动态库中的接口
复制代码 代码如下:
>>> lib.add(5,7)
12
两个参数的相加的函数如下:
复制代码 代码如下:
ufo@ufo:~/helloworld$ cat helloworld.c
#include
#include int add(int a, int b)
{
    int c = a + b;
    return c;
}
编译动态库的命令行:
复制代码 代码如下:
gcc -shared -fpic -dpic helloworld.c -o libhelloworld.so.0.0.0
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product