加入收藏 | 设为首页 | 会员中心 | 我要投稿 常州站长网 (https://www.0519zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 教程 > 正文

一个简单的C共享库的创建及Python调用此库的

发布时间:2021-11-19 16:17:22 所属栏目:教程 来源:互联网
导读:/********************************************************************* * Author : Samson * Date : 02/02/2015 * Test platform: * 3.13.0-24-generic * GNU bash, 4.3.11(1)-release * *************************************************************

/*********************************************************************
 * 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
 
linuxidc@linuxidc:~/helloworld/.libs$ ll
总用量 32
drwxr-xr-x 2 linuxidc linuxidc 4096  1月 29 14:54 ./
drwxr-xr-x 6 linuxidc linuxidc 4096  1月 29 16:08 ../
-rw-r--r-- 1 linuxidc linuxidc 3816  1月 29 14:54 helloworld.o
-rw-r--r-- 1 linuxidc linuxidc 3956  1月 29 14:54 libhelloworld.a
lrwxrwxrwx 1 linuxidc linuxidc  19  1月 29 14:54 libhelloworld.la -> ../libhelloworld.la
-rw-r--r-- 1 linuxidc linuxidc  983  1月 29 14:54 libhelloworld.lai
lrwxrwxrwx 1 linuxidc linuxidc  22  1月 29 14:54 libhelloworld.so -> libhelloworld.so.0.0.0*
lrwxrwxrwx 1 linuxidc linuxidc  22  1月 29 14:54 libhelloworld.so.0 -> libhelloworld.so.0.0.0*
-rwxr-xr-x 1 linuxidc linuxidc 9038  1月 29 14:54 libhelloworld.so.0.0.0*
 
 
进入python的命令行模式进行C语言实现的两个数值相加的程序的调用;
linuxidc@linuxidc:~/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
 
两个参数的相加的函数如下:
 
linuxidc@linuxidc:~/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

(编辑:常州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读