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
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.]
>>>
详细的内容大家可以参考: