一个简单的C共享库的创建及python调用此库的方法

来源:互联网 发布:美丽折淘客软件下载 编辑:程序博客网 时间:2024/05/22 15:23
/********************************************************************* * Author  : Samson * Date    : 02/02/2015 * Test platform: *              3.13.0-24-generic *              GNU bash, 4.3.11(1)-release  * *******************************************************************/

在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

Ref:
http://tool.oschina.net/uploads/apidocs/python2.7.3/library/ctypes.html

0 0
原创粉丝点击