使用f2py将C语言的函数转换为python模块

来源:互联网 发布:知乎 找工作 编辑:程序博客网 时间:2024/05/20 19:46

f2py本来是用来转换fortran代码的,其实也可以转换c语言的代码,只是要自己写一个签名文件吧了!

以前都是用swig做的,现在发现用f2py其实更简单一点,但是对不懂fortran的人,还是使用swig较好.

因为接口文件(或签名文件的格式类似Fortran,而不是C语言).

请看示例:

/* File foo.c */void foo(int n, double *x, double *y) {  int i;  for (i=0;i<n;i++) {    y[i] = x[i] + i;  }}


再编写一个签名文件

! File m.pyfpython module minterface  subroutine foo(n,x,y)    intent(c) foo                 ! foo is a C function    intent(c)                     ! all foo arguments are                                   ! considered as C based    integer intent(hide), depend(x) :: n=len(x)  ! n is the length                                                 ! of input array x    double precision intent(in) :: x(n)          ! x is input array                                                  ! (or  arbitrary sequence)    double precision intent(out) :: y(n)         ! y is output array,                                                  ! see code in foo.c  end subroutine fooend interfaceend python module m


使用命令行编译一下即可,在DOS窗口输入:

f2py m.pyf foo.c -c

下面就可以再Python中使用了这个模块了

>>> import m>>> print m.__doc__This module 'm' is auto-generated with f2py (version:2_2130).Functions:  y = foo(x).>>> print m.foo.__doc__foo - Function signature:  y = foo(x)Required arguments:  x : input rank-1 array('d') with bounds (n)Return objects:  y : rank-1 array('d') with bounds (n)>>> print m.foo([1,2,3,4,5])    [ 1.  3.  5.  7.  9.]>>>


详细的内容大家可以参考:

http://www.scipy.org/Cookbook/f2py_and_NumPy

原创粉丝点击