是否可以将fortran 77函数作为回调函数指针传递给C/C++?如果是这样的话,是怎么做的?
我在网上找到的信息与fortran 90和更高版本有关,但我的遗留代码库是77。
非常感谢
发布于 2010-05-25 13:38:05
如果它可以在FORTRAN 77中完成,那么它将是特定于编译器和平台的。Fortran 2003的新的ISO C绑定提供了一种混合Fortran和C的标准方法,以及任何遵循或可以遵循C调用约定的语言,如C++。虽然Fortran 2003正式是Fortran 2003的一部分,而且完全支持整个Fortran 2003的Fortran编译器非常少,但很多Fortran 95编译器都支持ISO C绑定,包括gfortran、g95、Sun、ifort等。因此,我建议使用这些Fortran 95编译器之一和ISO C绑定方法,而不是为特定的方法找出某种方法。既然FORTRAN 77是Fortran 95的子集,为什么不使用这些编译器之一来编译您的遗留代码,使用Fortran 95来添加这个新功能呢?
我已经使用ISO C绑定从C调用了Fortran过程,但还没有将它们作为指针传递。这应该是可能的。具体步骤如下:
1)使用Bind(C)属性声明Fortran函数,
2)使用特殊类型声明所有参数,例如integer(c_int),它们与C的类型相匹配。
第1步和第2步使Fortran函数可以与C进行互操作。
3)使用Fortran内部函数"c_funloc“获得指向此Fortran函数的C指针,并将指针值赋给类型为"c_funptr”的指针。
4)在Fortran代码中,使用接口声明要将函数指针传递到的C例程,在Fortran术语中声明它,但使用Bind(C)属性和可互操作的类型,以便Fortran编译器知道要使用C调用约定-使C例程可与Fortran互操作。
然后,当您在Fortran代码中调用C例程时,可以将步骤3中创建的函数指针传递给它。
更新:代码示例: Fortran主程序"test_func_pointer“将指向Fortran函数"my_poly”的指针传递给C例程"C_Func_using_Func_ptr“,并从该C函数接收返回的结果。
module func_pointer_mod
use, intrinsic :: iso_c_binding
implicit none
interface C_func_interface
function C_Func_using_Func_ptr ( x, Func_ptr ) bind (C, name="C_Func_using_Func_ptr")
import
real (c_float) :: C_Func_using_Func_ptr
real (c_float), VALUE, intent (in) :: x
type (c_funptr), VALUE, intent (in) :: Func_ptr
end function C_Func_using_Func_ptr
end interface C_func_interface
contains
function my_poly (x) bind (C, name="my_poly")
real (c_float) :: my_poly
real (c_float), VALUE, intent (in) :: x
my_poly = 2.0 * x**2 + 3.0 * x + 5.0
return
end function my_poly
end module func_pointer_mod
program test_func_pointer
use, intrinsic :: iso_c_binding
use func_pointer_mod
implicit none
type (c_funptr) :: C_func_ptr
C_func_ptr = c_funloc ( my_poly )
write (*, *) C_Func_using_Func_ptr ( 2.5_c_float, C_func_ptr )
stop
end program test_func_pointer和
float C_Func_using_Func_ptr (
float x,
float (*Func_ptr) (float y)
) {
return ( (*Func_ptr) (x) );
}https://stackoverflow.com/questions/2902186
复制相似问题