python 调用c语言函数的方法

作者:fk12138 时间:2023-12-11 17:24:21 

虽然python是万能的,但是对于某些特殊功能,需要c语言才能完成。这样,就需要用python来调用c的代码了

具体流程:

c编写相关函数 ,编译成库

然后在python中加载这些库,指定调用函数。

这些函数可以char ,int, float, 还能返回指针。

以下示例:

通过python调用c函数,返回"hello,world 字符串"

新建c语言文件 hello.c

touch hello.c


#include <stdio.h>

char *get_str()
{
 return "hello,world"
}

编译成库

gcc -o hello.so --share -fPIC hello.c

新建python脚本

touch test.py


from ctypes import *

dll = CDLL("./hello.so")
dll.get_str.restype = c_char_p
str = dll.get_str()
print(string_at(str, 11))

执行python脚本


[feng@arch python_c]$ python test.py
hello,world

来源:http://www.cnblogs.com/0x12345678/p/6530022.html?utm_source=tuicool&utm_medium=referral

标签:python,c语言
0
投稿

猜你喜欢

  • python面向对象基础之常用魔术方法

    2021-08-20 20:08:59
  • 09年QQ登录Banner之转变

    2009-02-16 12:53:00
  • Windows下anaconda安装第三方包的方法小结(tensorflow、gensim为例)

    2021-09-14 00:22:11
  • php+lottery.js实现九宫格抽奖功能

    2024-04-17 10:34:28
  • python 删除指定时间间隔之前的文件实例

    2023-07-19 17:58:38
  • 详谈python中subprocess shell=False与shell=True的区别

    2021-08-01 02:00:01
  • JavaScript Generator异步过度的实现详解

    2024-04-29 13:45:26
  • python和mysql交互操作实例详解【基于pymysql库】

    2024-01-16 01:03:47
  • HTML5实现留言和回复页面样式

    2024-04-18 10:32:20
  • python实现连续变量最优分箱详解--CART算法

    2023-01-15 16:33:05
  • selenium+python设置爬虫代理IP的方法

    2021-10-01 11:14:33
  • Python学习之线程池与GIL全局锁详解

    2021-10-09 21:55:18
  • Python ChineseCalendar包主要类和方法详解

    2021-10-12 10:40:40
  • SqlServer表死锁的解决方法分享

    2011-09-30 11:16:16
  • 复制SqlServer数据库的方法

    2024-01-26 22:46:26
  • Python简单实现区域生长方式

    2023-08-08 12:07:38
  • 撤回我也能看到!教你用Python制作微信防撤回脚本

    2021-08-05 14:38:30
  • MySQL 使用SQL语句修改表名的实现

    2024-01-17 09:14:31
  • 关于windows下Tensorflow和pytorch安装教程

    2023-06-09 07:35:54
  • Python学习笔记之open()函数打开文件路径报错问题

    2021-10-05 23:25:34
  • asp之家 网络编程 m.aspxhome.com