pointers - 如何使用 c_ptr 拥有一个具有不同类型参数的 Fortran 函数?

标签 pointers fortran fortran-iso-c-binding

我读了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/

相关文章:

c - 在 Fortran 和 C 之间交换数组

c - 链表实现内存分配

c - 该程序中的内存是如何分配的?

oop - Fortran 容器类会自动调用包含对象的析构函数吗?

C++ 类函数调用 fortran 子例程

c - 将 FORTRAN 对象传递给 C,反之亦然

从 void 到 MPI_Aint 的转换

c++ - 如何在 C++ 中为指针分配常量地址?

c++ - 在 C++ 中重新分配指针的正确方法

c++ - 将 C++ 程序与 Fortran 库链接时对 _rpoly_ 的 undefined reference