• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > Python调用C语言开发的共享库方法实例

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

作者:junjie 字体:[增加 减小] 来源:互联网

junjie 通过本文主要向大家介绍了python与c语言,python与c语言的区别,python跟c语言,c语言调用python,c语言调用python脚本等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

在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*
</div>
进入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.
</div>
载入ctypes类(此类即是调用C语言动态库的方法)
>>> import ctypes
</div>
打开当前目录的动态库
>>> lib=ctypes.cdll.LoadLibrary("./libhelloworld.so.0.0.0")
</div>
调用动态库中的接口
>>> lib.add(5,7)
12
</div>
两个参数的相加的函数如下:
ufo@ufo:~/helloworld$ cat helloworld.c
#include <stdio.h>
#include <stdlib.h>

int add(int a, int b)
{
    int c = a + b;
    return c;
}
</div>
编译动态库的命令行:
gcc -shared -fPIC -DPIC helloworld.c -o libhelloworld.so.0.0.0
</div>

</div>

您可能想查找下面的文章:

  • 使用C语言扩展Python程序的简单入门指引
  • Python调用C语言开发的共享库方法实例

相关文章

  • Python实现的ini文件操作类分享
  • Python实现图像几何变换
  • python返回昨天日期的方法
  • Python利用前序和中序遍历结果重建二叉树的方法
  • python解析基于xml格式的日志文件
  • 高性能web服务器框架Tornado简单实现restful接口及开发实例
  • Python生成随机MAC地址
  • Python 基于Twisted框架的文件夹网络传输源码
  • Linux下通过python访问MySQL、Oracle、SQL Server数据库的方法
  • python入门基础之用户输入与模块初认识

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • Python基于sftp及rsa密匙实现远程拷贝文件的方法
    • Django Admin实现上传图片校验功能
    • 在Python中使用SQLite的简单教程
    • Python六大开源框架对比
    • Pyramid Mako模板引入helper对象的步骤方法
    • Python脚本实现集群检测和管理功能
    • 深入解析Python中的线程同步方法
    • Pyramid添加Middleware的方法实例
    • 举例讲解Django中数据模型访问外键值的方法
    • Python使用multiprocessing实现一个最简单的分布式作业调度系统

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有