接下来,介绍一个简单的例子,从fortran中传递并返回一维自定义结构体数组到python
注意点:
1、fortran新标准支持可分配数组作为变量传入并在subroutine或function分配后返回;
2、BIND不支持传入可分配数组(也即1和2无法同时使用);
3、fortran没有垃圾自动回收机制;
综合上述3点,利用ctypes调用fortran不能也不宜直接返回形状大小在计算前无法确定的数组,折衷的办法是:
a、估算出返回数组的大小,可以适当偏大;
b、在fortran的module定义全局可分配数组,第一次调用后存储结果并返回数组形状数值,在python中利用numpy开辟空数组,再次调用fortran得到结果并清空fortran中module的全局变量
fortran代码:

module sam
use,intrinsic::iso_c_binding
implicit none
type,bind(C)::abc
!Define struct
character(len=)::nam
real(c_float)::val()
end type
! Global variable in fortran module
! Notice: dealloacte after using to avoid memory leak
type(abc),allocatable::stu(:)
contains
subroutine calc(input,output,n1)bind(c,name='ex01')
! Example
! Both in and out variables has assumed shape
! Bind(C) not allowed pass alloctable variables
! Pure Fortran2008 allows pass alloctable array to subroutine to allocate or deallocate
implicit none
integer(c_int),intent(in),value::n1
real(c_float),intent(in)::input(n1)
type(abc),intent(out)::output(*n1) integer::i do i=,size(output)
output(i)%nam = "abcdefea"
output(i)%val(:) = real(i-,)
output(i)%val(::) = i*2.5E0
enddo
return
end subroutine subroutine calc2(input,n1,n2)bind(c,name='ex02_1')
! Example 02_1
! Return result's shape
implicit none
integer(c_int),intent(in),value::n1
real(c_float),intent(in)::input(n1)
integer(c_int),intent(out)::n2 integer::i,j call clear()
if(input()<.E0)then
allocate(stu())
else
allocate(stu(int(input())+))
endif
do i=,size(stu)
stu(i)%nam = "daefvdefefadfad"
do j=,size(stu(i)%val)
stu(i)%val(j) = i*j*1.5E0
enddo
enddo
n2 = size(stu)
return
end subroutine subroutine getdata(output,n)bind(c,name='ex02_2')
! Example 02_2
! Return result and do clear
implicit none
integer(c_int),intent(in),value::n
type(abc),intent(out)::output(n) output = stu
call clear()
return
end subroutine subroutine clear()
implicit none
if(allocated(stu))deallocate(stu)
end subroutine
end module program test
use sam
implicit none
real(c_float)::array()
type(abc)::student(*)
integer::i array = [.E0,.E0,.E0,.E0,.E0]
call calc(array,student,)
do i=,size(student)
write(*,*)student(i)%nam,student(i)%val
enddo
end program

python代码:

 #! /usr/bin/env python
#coding=utf-8 '''
A short example of use ctypes and numpy to call fortran dynamic library
example for 1d struct array pass or access
'''
import numpy as np
from numpy.ctypeslib import load_library,ndpointer
from ctypes import c_int #define struct as same sa fortran
abc = np.dtype([("nam",'S80',1),("val",'f4',10)])
#load dynamic library
flib = load_library("libexample",".")
#function handle of ex01
fun01 = flib.ex01
#define input arguments
fun01.argtypes = [ndpointer('f4'),ndpointer(abc),c_int]
#
n1,n2 = 5,np.array(0,'i4')
vec = np.zeros((n1,),'f4')
student = np.empty((n1*2,),abc)
#print vec
fun01(vec,student,n1)
#print student
#function handle of ex02_1
fun02_1 = flib.ex02_1
fun02_1.argtypes = [ndpointer('f4'),c_int,ndpointer('i4')]
fun02_1(vec,n1,n2)
#print n1,n2
#function handle of ex02_2
fun02_2 = flib.ex02_2
fun02_2.argtypes = [ndpointer(abc),c_int]
student2 = np.empty((n2,),abc)
fun02_2(student2,n2)
print student2

编译命令:

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

Python调用C/Fortran混合的动态链接库--中篇的更多相关文章

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

    内容描述: 在32位或64位的windows或GNU/Linux系统下利用Python的ctypes和numpy模块调用C/Fortran混合编程的有限元数值计算程序 操作系统及编译环境: 32bit ...

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

    接着前面的内容,我们在这里继续介绍Python传递二维数组到fortran并进行简单计算后返回的例子. 问题描述: module py2f90 use,intrinsic::iso_c_binding ...

  3. Python调用C的DLL(动态链接库)

    开发环境:mingw64位,python3.6 64位 参考博客: mingw编译dll: https://blog.csdn.net/liyuanbhu/article/details/426123 ...

  4. Python调用DLL动态链接库——ctypes使用

    最近要使用python调用C++编译生成的DLL动态链接库,因此学习了一下ctypes库的基本使用. ctypes是一个用于Python的外部函数库,它提供C兼容的数据类型,并允许在DLL或共享库中调 ...

  5. [转载:]C#与Fortran混合编程之本地调用Fortran动态链接库

    前言 C#发展到现在,已是一门相当完善的语言,他基于C语言风格,演化于C++.并依靠强大的.NET底层框架.C#可以用来快速构建桌面及Web应用.然而在我们的实际工作中,尽管C#已经非常完善,但还是不 ...

  6. Python调用C/C++动态链接库

    Python调用C/C++动态链接库 2013年07月26日 ⁄ 综合 ⁄ 共 3219字 ⁄ 字号 小 中 大 ⁄ 评论关闭   吐槽(可略过):不知不觉,4月份毕业,5月份进入团队,已有7个月.大 ...

  7. Python调用C/C++动态链接库的方法详解

    Python调用C/C++动态链接库的方法详解 投稿:shichen2014 这篇文章主要介绍了Python调用C/C++动态链接库的方法,需要的朋友可以参考下 本文以实例讲解了Python调用C/C ...

  8. Python的扩展接口[2] -> 动态链接库DLL[1] -> 组件对象模型 COM 的 Python 调用

    组件对象模型 COM 的 Python 调用 关于COM的基本概念,可参考组件对象模型 COM的内容,下面主要介绍两种使用 Python 调用 COM 组件的方法. 1 使用 win32com 1.1 ...

  9. python调用C/C++动态链接库和jython

    总结(非原创) Python调用C库比较简单,不经过任何封装打包成so,再使用python的ctypes调用即可. 1. C语言文件:pycall.c #include <stdio.h> ...

随机推荐

  1. main()中的参数argc, argv

    转自:http://blog.csdn.net/eastmount/article/details/20413773 一.main()函数参数 通常我们在写主函数时都是void main()或int ...

  2. HDu-1247 Hat’s Words,字典树裸模板!

    Hat's Words 题意:给出一张单词表求有多少个单词是由单词表里的两个单词组成,可以重复!按字典序输出这些单词. 思路:先建一个字典树,然后枚举每个单词,把每个单词任意拆分两部分然后查找. 目测 ...

  3. HDU 5073 Galaxy ——乱搞

    [题目分析] 练习赛的T1. 只要看懂样例就可以猜结论了. 然后大胆猜测剩下的星星是一段,其余的都移到重心上去. 所以只要把计算的式子变形一下就很好维护了. 居然没有1A [代码] #include ...

  4. [BZOJ1594] [Usaco2008 Jan]猜数游戏(二分 + 并查集)

    传送门 题中重要信息,每堆草的数量都不一样. 可以思考一下,什么情况下才会出现矛盾. 1.如果两个区间的最小值一样,但是这两个区间没有交集,那么就出现矛盾. 2.如果两个区间的最小值一样,并且这两个区 ...

  5. 算法复习——序列分治(ssoj光荣的梦想)

    题目: 题目描述 Prince对他在这片大陆上维护的秩序感到满意,于是决定启程离开艾泽拉斯.在他动身之前,Prince决定赋予King_Bette最强大的能量以守护世界.保卫这里的平衡与和谐.在那个时 ...

  6. VS的一些错误解决方法记录

    1.errorC2664 "bool CMarkup::AddElem(MCD_CSTR,MCD_CSTR,int)":不能将参数1从“constchar [7]” 转换位&quo ...

  7. 解决U3D4.1.5或以上无法启动MONODEV的方法

    通常会报这样的错误 System.EntryPointNotFoundException: Unable to find an entry point named 'gtksharp_list_get ...

  8. [UIScreen mainScreen].applicationFrame与[UIScreen mainScreen].bounds区别

    [UIScreen mainScreen].applicationFrame与[UIScreen mainScreen].bounds区别: applicationFrame会自动判断是否存在状态栏, ...

  9. Day 2 操作系统基础

    课前复习新知识 RAID(Redundant Arrays of Independent Disks)独立冗余磁盘阵列 定义:加州大学伯克利分校1987年提出,最初是为了组合小的廉价磁盘来代替大的昂贵 ...

  10. SGU 分类

    http://acm.sgu.ru/problemset.php?contest=0&volume=1 101 Domino 欧拉路 102 Coprime 枚举/数学方法 103 Traff ...