我读了Type Casting in Callbacks of the article Fortran Best practices部分.
我想在我的程序中使用使用类型(c_ptr)指针
中描述的内容但我有一个问题。我概述了我尝试做的事情。我希望这足以理解。否则,请告诉我,我将发布完整的示例。
我有两种类型,我用一种或另一种类型调用相同的子例程。我的子例程的第一个参数是一个整数,表示第二个参数的类型(type1_t或type2_t)
type type1_t
real :: a, b
integer :: c
end type1_t
type type2_t
real :: a,e
integer :: b,c,d
end type2_t
type(type1_t) :: type1
! ... init of type1
type(type2_t) :: type2
! ... init of type2_t
call myfoo(1,c_loc(type_1))
call myfoo(2,c_loc(type_2))
但是现在,我在 myfoo 中的声明遇到了问题,因为在 fortran 中声明必须在指令之前完成。
我知道以下代码不起作用:
subroutine myfoo(i, params)
integer, intent(in) :: i
type(c_ptr), intent(in) :: params
if (i == 1) then
type(type1_t), pointer :: pars
elseif (i ==2) then
type(type2_t), pointer :: pars
endif
call c_f_pointer(params, pars)
! do some stuff with pars (there are common parts of code either the dummy args is type_1 or type_2). For example, the line above.
end subroutine myfoo
如果我使用 block 构造,则会遇到问题,因为变量在 block 末尾消失。
如何使用c_ptr解决这个问题?
最佳答案
实现此目的的一个简单方法是将特定于类型的代码放入模块中的两个单独的例程中,并使用接口(interface)绑定(bind)它们,这样编译器将根据输入上提供的变量的类型选择正确的子例程:
module blabla
private
public :: foo
interface foo
module procedure foo1
module procedure foo2
end interface
contains
subroutine foo1(params)
type(t1) :: params
! Do cool stuff
end subroutine foo1
subroutine foo2(params)
type(t2) :: params
! Do type-2 cool stuff here
end subroutine foo2
end module blabla
关于pointers - 如何使用 c_ptr 拥有一个具有不同类型参数的 Fortran 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72535742/