接着前面的內容,我們在這里繼續介紹Python傳遞二維數組到fortran並進行簡單計算后返回的例子。
問題描述:
Python的NumPy定義二維數組傳遞到Fortran程序計算后返回
限制條件:
- Python中必須確定數組的大小即維數
- 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.]]