📜  如何在Python调用C函数

📅  最后修改于: 2021-05-20 07:50:09             🧑  作者: Mango

您是否遇到过必须使用Python调用C函数的情况?本文将在一个非常基础的水平上为您提供帮助,如果您没有遇到过这种情况,您将很高兴知道如何实现。
首先,让我们使用C编写一个简单的函数,并生成文件的共享库。假设文件名是函数.c。

C
int myFunction(int num)
{
    if (num == 0)
 
        // if number is 0, do not perform any operation.
        return 0;
    else
        // if number is power of 2, return 1 else return 0
          return ((num & (num - 1)) == 0 ? 1 : 0) ;
 
}


Python3
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 = ctypes.CDLL("libfun.so") # Or full path to file 
# 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)


编译:

cc -fPIC -shared -o libfun.so function.c

使用ctypes(外部函数接口)库从Python调用C函数

上面的语句将生成一个名为libfun.so的共享库。现在,让我们看看如何在Python使用它。在Python,我们有一个名为ctypes的库。使用这个库,我们可以在Python使用C函数。
假设文件名是函数.py。

Python3

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 = ctypes.CDLL("libfun.so") # Or full path to file 
# 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)