本文摘自php中文网,作者藏色散人,侵删。
您是否遇到过必须使用python调用C函数的情况?本文将在非常基础的层面为您提供帮助,如果您没有遇到过这种情况,您会很高兴知道它是如何实现的。
首先,让我们用C编写一个简单的函数,并生成该文件的共享库。假设文件名是function.c。
1 2 3 4 5 6 7 8 9 10 11 | int myFunction(int num)
{
if (num == 0)
return 0;
else
num & (num - 1) == 0 ? return 1 : return 0
}
|
编译:
1 | cc -fPIC -shared -o libfun.so function .c
|
使用ctypes(外部函数接口)库从Python调用C函数
上面的语句将生成一个名为libfun.so的共享库。现在,让我们看看如何在python中使用它。在python中,我们有一个名为ctypes的库。使用这个库我们可以在python中使用C函数。
假设文件名是function.py。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import ctypes
NUM = 16
# libfun loaded to the python file
# using fun.myFunction(),
# C function can be accessed
# but type of argument is the problem.
fun = ctype.CDLL(libfun.so)
# Now whenever argument
# will be passed to the function
# ctypes will check it.
fun.myFunction.argtypes(ctypes.c_int)
# now we can call this
# function using instant (fun)
# returnValue is the value
# return by function written in C
# code
returnVale = fun.myFunction(NUM)
|
本篇文章就是关于在Python中调用C函数的方法介绍,希望对需要的朋友有所帮助!
以上就是如何在Python中调用C函数的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
使用geany运行Python
流畅的Python适合入门吗
Python获取代理ip的实例分享
用 Python 连接 mysql 的几种方式详解_Python
django如何配置mysql数据库
使用pandas进行数据处理之 series篇
学会Python能做什么工作
Python和163邮箱授权码发送邮件的分析与实现(代码)
Python中的中括号是什么意思
Python如何缩进
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » 如何在Python中调用C函数