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

yipeiwu_com7年前Python基础

在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 <stdio.h>
#include <stdlib.h>

int add(int a, int b)
{
    int c = a + b;
    return c;
}


编译动态库的命令行:
复制代码 代码如下:

gcc -shared -fPIC -DPIC helloworld.c -o libhelloworld.so.0.0.0

相关文章

TensorFlow 合并/连接数组的方法

如下所示: import tensorflow as tf a = tf.Variable([4,5,6]) b = tf.Variable([1,2,3]) c = tf.co...

python3调用R的示例代码

由于工作需要,在做最优分箱的时候,始终写不出来高效的代码,所以就找到了R语言中的最优分箱的包,这个时候考虑到了在python中调用R语言,完美结合。在国内的中文网站搜了半天,搭建环境的时...

对python中for、if、while的区别与比较方法

如下所示: if应用举例: #if 若条件成立,只执行一次 #if 条件:如果条件成立,执行条件后的代码块内容,不成立,直接跳过代码块 #判断如果年龄age小于18,输出未成年 #=...

python正则表达式的使用

python的正则是通过re模块的支持 匹配的3个函数 match :只从字符串的开始与正则表达式匹配,匹配成功返回matchobject,否则返回none; re.match(patt...

使用graphics.py实现2048小游戏

使用graphics.py实现2048小游戏

1、过年的时候在手机上下载了2048玩了几天,心血来潮决定用py写一个,刚开始的时候想用QT实现,发现依赖有点大。正好看到graphics.py是基于tkinter做的封装就拿来练手,并...