Next, we'll continue here to introduce Python's example of passing a two-dimensional array to Fortran and returning it with a simple calculation.
Problem Description:
Python NumPy defines a two-dimensional array that is passed to the FORTRAN program after the calculation is returned
Restrictions:
- In Python, you must determine the size and dimension of the array
- The array stored in Python, defined in NumPy, must be a FORTRAN, column-based store
Implementation method:
Python uses NumPy to define a two-dimensional array stored in FORTRAN, using Ndpointer to define array types and dimensions, and to pass the first address and dimension information of a two-dimensional array into Fortran for calculation and return
Note: NumPy's Ndarray provides the cTYPES module, which can call its data property to pass in the first address of the array
Reference Links:
The original NumPy array can be easily combined with the ctypes.
Fortran code:
1 Module Py2f902 use,intrinsic::iso_c_binding3 ImplicitNone4 contains5Subroutine Transfermat2for (MATRIX,N1,N2) bind (c,name='array2py')6 ImplicitNone7Integer (C_int), intent (inch), Value::n1,n28Real (C_float), intent ( out):: Matrix (N1,N2)9Ten integer::i,j One!Initialize Matrix AMatrix =0.0E0 -!Loop - DoI=1, N1 the Doj=1, N2 -Matrix (I,J) = Real (I,4)*1. E1+real (J,4)*2. E0 -Write (*,"(' Row: ', i4,1x, ' Col: ', i4,1x, ' Value: ', 1x,f5.2)") I,j,matrix (i,j) - Enddo + Enddo - return + End subroutine A End Module at - Program Test - Use py2f90 - ImplicitNone -Real (kind=4):: AA (4,5) -Call Transfermat2for (AA,4,5) inEnd Program
Python code:
1 #!/usr/bin/env python2 #Coding=utf-834 ImportNumPy as NP5 fromNumpy.ctypeslibImportLoad_library,ndpointer6 fromcTYPESImportC_int78 #shape of 2d array9N1,N2 = 2,4+1Ten #Create an empty 2d array Onedata = Np.empty (shape= (n1,n2), dtype='f4', order='F') A -Flib = Load_library ("Test","./") -Flib.argtypes = [Ndpointer (dtype='f4', ndim=2), C_int,c_int] the flib.array2py (DATA.CTYPES.DATA,N1,N2) - Print "*"*80 - PrintData
Compile Instructions:
Gfortran Ctypes2d_array_test.f90-fpic-shared-o test.so
Operation Result:
[Email protected]:~/fortran_code$ python py2f90_test.pyrow:1Col:1Value:12.00Row:1Col:2Value:14.00Row:1Col:3Value:16.00Row:1Col:4Value:18.00Row:1Col:5Value:20.00Row:2Col:1Value:22.00Row:2Col:2Value:24.00Row:2Col:3Value:26.00Row:2Col:4Value:28.00Row:2Col:5Value:30.00********************************************************************************[[ A. -. -. -. -.] [ A. -. -. -. -.]]
?
Python calls C/fortran mixed dynamic link library-Next