Python调用C/Fortran混合的动态链接库-下篇

接着前面的内容,我们在这里继续介绍Python传递二维数组到fortran并进行简单计算后返回的例子。

问题描述:

Python的NumPy定义二维数组传递到Fortran程序计算后返回


限制条件:

  1. Python中必须确定数组的大小即维数
  2. Python中用NumPy定义的数组存储方式必须是Fortran的按列存储

实现方式:

Python中使用NumPy定义Fortran方式存储的二维数组,利用ndpointer定义数组类型和维数,将二维数组的首地址和维数信息传入Fortran中进行计算并返回

附注:NumPy的ndarray提供了ctypes模块,可以调用其data属性将数组首地址传入

参考链接:

原来Numpy的array可以很方便地和ctypes结合起来使用

Fortran代码:

 1 module py2f90
 2 use,intrinsic::iso_c_binding
 3 implicit none
 4 contains
 5     subroutine transferMat2For(matrix,n1,n2)bind(c,name='array2py')
 6     implicit none
 7     integer(c_int),intent(in),value::n1,n2
 8     real(c_float),intent(out)::matrix(n1,n2)
 9
10     integer::i,j
11     ! initialize matrix
12     matrix = 0.0E0
13     ! loop
14     do i=1,n1
15         do j=1,n2
16             matrix(i,j) = real(i,4)*1.E1+real(j,4)*2.E0
17             write(*,"('Row:',i4,1x,'Col:',i4,1x,'Value:',1x,F5.2)")i,j,matrix(i,j)
18         enddo
19     enddo
20     return
21     end subroutine
22 end module
23
24 program test
25 use py2f90
26 implicit none
27 real(kind=4)::aa(4,5)
28 call transferMat2For(aa,4,5)
29 end program

Python代码:

 1 #! /usr/bin/env python
 2 #coding=utf-8
 3
 4 import numpy as np
 5 from numpy.ctypeslib import load_library,ndpointer
 6 from ctypes import c_int
 7
 8 # shape of 2d array
 9 n1,n2 = 2,4+1
10 # create an empty 2d array
11 data = np.empty(shape=(n1,n2),dtype='f4',order='f')
12
13 flib = load_library("test","./")
14 flib.argtypes = [ndpointer(dtype='f4',ndim=2),c_int,c_int]
15 flib.array2py(data.ctypes.data,n1,n2)
16 print "*"*80
17 print data

编译指令:

gfortran ctypes2d_array_test.f90 -fPIC -shared -o test.so

运行结果:

pasuka@ubuntu:~/fortran_code$ python py2f90_test.py
Row:   1 Col:   1 Value: 12.00
Row:   1 Col:   2 Value: 14.00
Row:   1 Col:   3 Value: 16.00
Row:   1 Col:   4 Value: 18.00
Row:   1 Col:   5 Value: 20.00
Row:   2 Col:   1 Value: 22.00
Row:   2 Col:   2 Value: 24.00
Row:   2 Col:   3 Value: 26.00
Row:   2 Col:   4 Value: 28.00
Row:   2 Col:   5 Value: 30.00
********************************************************************************
[[ 12.  14.  16.  18.  20.]
 [ 22.  24.  26.  28.  30.]]

 

posted @ 2014-10-09 08:28  pasuka  阅读(4096)  评论(0编辑  收藏  举报