当前位置:Gxlcms > Python > 如何在Python中调用C函数

如何在Python中调用C函数

时间:2021-07-01 10:21:17 帮助过:62人阅读

您是否遇到过必须使用python调用C函数的情况?本文将在非常基础的层面为您提供帮助,如果您没有遇到过这种情况,您会很高兴知道它是如何实现的。

首先,让我们用C编写一个简单的函数,并生成该文件的共享库。假设文件名是function.c。

  1. int myFunction(int num)
  2. {
  3. if (num == 0)
  4. //如果number为0,则不执行任何操作。
  5. return 0;
  6. else
  7. // 如果number是2的幂,则返回1,否则返回0
  8. num & (num - 1) == 0 ? return 1 : return 0
  9. }

编译:

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

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

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

假设文件名是function.py。

  1. import ctypes
  2. NUM = 16
  3. # libfun loaded to the python file
  4. # using fun.myFunction(),
  5. # C function can be accessed
  6. # but type of argument is the problem.
  7. fun = ctype.CDLL(libfun.so)
  8. # Now whenever argument
  9. # will be passed to the function
  10. # ctypes will check it.
  11. fun.myFunction.argtypes(ctypes.c_int)
  12. # now we can call this
  13. # function using instant (fun)
  14. # returnValue is the value
  15. # return by function written in C
  16. # code
  17. returnVale = fun.myFunction(NUM)

本篇文章就是关于在Python中调用C函数的方法介绍,希望对需要的朋友有所帮助!

以上就是如何在Python中调用C函数的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行