andy8496 发表于 2019-11-12 12:36:30

用ISO_C_BINDING混编

本帖最后由 andy8496 于 2019-11-12 12:42 编辑

因为某些不得已的原因,不得不做C和Fortran的混编。简单说来就是要在C的代码中调用Fortran的动态链接库。目前的环境是VS2012+Intel Parallel Studio XE 2015
以下是从文档中找到的关于ISO_C_BINDING的例子:

Example of C Calling Fortran The following examplecalls a Fortran subroutine called Simulation. This subroutine corresponds to theC void function simulation. Fortran Code Example subroutine Simulation(alpha, beta, gamma, delta, arrays) BIND(C)

use, intrinsic :: ISO_C_BINDING

implicit none

integer (C_LONG), value :: alpha

real (C_DOUBLE), intent(inout) :: beta

integer (C_LONG), intent(out) :: gamma

real (C_DOUBLE),dimension(*),intent(in) :: delta



type, BIND(C) :: pass

integer (C_INT) :: lenc, lenf

type (C_PTR) :: c, f

end type pass



type (pass), intent(inout) :: arrays

real (C_FLOAT), ALLOCATABLE, target, save :: eta(:)real (C_FLOAT), pointer :: c_array(:)

...

! Associate c_array with an array allocated in C

call C_F_POINTER (arrays%c, c_array, (/arrays%lenc/) )

...

! Allocate an array and make it available in C

arrays%lenf = 100

ALLOCATE (eta(arrays%lenf))

arrays%f = c_loc(eta)

...

end subroutine SimulationC Struct declaration Example struct pass {int lenc,lenf; float *c, *f;}; C Function Prototype Example void simulation(longalpha, double *beta, long *gamma, double delta[], struct pass *arrays); C Calling sequence Example simulation(alpha,&beta, &gamma, delta, &arrays); 我想请教的问题:
采用上述这种方式混编的时候,直接在Fortran代码中按照上述方式编码,然后编译成Dll,就能在C中调用吗?还是仍然需要添加:
!DEC$ ATTRIBUTES STDCALL,REFERENCE,DLLEXPORT,ALIAS: ...
这种语句?我两种方式都做过尝试,但是不知道什么原因,都没有成功。所以希望有一个明确一点的方向继续尝试。

多谢各位大神赐教!

vvt 发表于 2019-11-12 13:13:46

!DEC$ ATTRIBUTES STDCALL,REFERENCE,DLLEXPORT,ALIAS: ...
不全部需要,只需要
!DEC$ ATTRIBUTES DLLEXPORT :: func_name

andy8496 发表于 2019-11-13 12:23:49

vvt 发表于 2019-11-12 13:13
!DEC$ ATTRIBUTES STDCALL,REFERENCE,DLLEXPORT,ALIAS: ...
不全部需要,只需要
!DEC$ ATTRIBUTES DLLEXPOR ...

OK了!多谢指点!

ErrorZero 发表于 2021-1-1 15:51:59

请问这个程序有没有完整的例子,我看了半天还是不会用啊https://cdn.jsdelivr.net/gh/hishis/forum-master/public/images/patch.gif
页: [1]
查看完整版本: 用ISO_C_BINDING混编