您的位置:首页 > 编程语言 > Python开发

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

2014-10-09 08:28 281 查看
接着前面的内容,我们在这里继续介绍Python传递二维数组到fortran并进行简单计算后返回的例子。

问题描述:

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

限制条件:

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

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

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

参考链接:

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

Fortran代码:

module py2f90
use,intrinsic::iso_c_binding
implicit none
contains
subroutine transferMat2For(matrix,n1,n2)bind(c,name='array2py')
implicit none
integer(c_int),intent(in),value::n1,n2
real(c_float),intent(out)::matrix(n1,n2)

integer::i,j
! initialize matrix
matrix = 0.0E0
! loop
do i=1,n1
do j=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
end module

program test
use py2f90
implicit none
real(kind=4)::aa(4,5)
call transferMat2For(aa,4,5)
end program
Python代码:

#! /usr/bin/env python
#coding=utf-8

import numpy as np
from numpy.ctypeslib import load_library,ndpointer
from ctypes import c_int

# shape of 2d array
n1,n2 = 2,4+1
# create an empty 2d array
data = np.empty(shape=(n1,n2),dtype='f4',order='f')

flib = load_library("test","./")
flib.argtypes = [ndpointer(dtype='f4',ndim=2),c_int,c_int]
flib.array2py(data.ctypes.data,n1,n2)
print "*"*80
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.]]
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: