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属性将数组首地址传入
参考链接:
问题描述:
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 programPython代码:
#! /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.]]
相关文章推荐
- [转载:]C#与Fortran混合编程之本地调用Fortran动态链接库
- Python调用C/Fortran混合的动态链接库--上篇
- Python调用C/Fortran混合的动态链接库--中篇
- C#与Fortran混合编程之本地调用Fortran动态链接库
- C#与Fortran混合编程之本地调用Fortran动态链接库
- VC 中调用Fortran动态链接库函数开发说明
- python调用动态链接库传送protobuf数据
- C++与Python的混合编程-调用有参函数以及C++数据类型与Python数据类型间的转换
- Python调用C/C++动态链接库的方法详解
- Python调用C/C++动态链接库的方法详解
- Python天天美味(29) - 调用VC++的动态链接库(DLL)
- f2py支持在fortran语言中调用其他Fortran函数或C代码或Python代码
- python中使用ctypes调用MinGW生成的动态链接库(dll)
- python中使用ctypes调用MinGW生成的动态链接库(dll)
- Python和VC混合调用的问题
- C++与Python的混合编程-环境配置与调用无参函数
- python调用动态链接库传送protobuf数据。
- Fortran 与C++的混合调用例程对应
- 用 WebService 实现 Silverlight 客户端调用第三方动态链接库(Fortran DLL)的具体过程
- Python调用C/C++动态链接库