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

22 篇文章 5 订阅
15 篇文章 0 订阅

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.pyf
python module m
interface
  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 foo
end interface
end 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

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值