fortran - 如何将 Fortran c_ptr 与 null 进行比较

标签 fortran fortran-iso-c-binding

我有一些需要组合的 Fortran 和 C 代码。

我正在使用一个看起来像这样的 Fortran 接口(interface):

module bridge
  use, intrinsic::iso_c_binding, only : c_ptr, c_null_ptr
  implicit none

  type(c_ptr) :: instance

  interface

    function c_init() result(this) bind(C, name="bridge_init")
      import
      type(c_ptr) :: this
    end function c_init

  end interface

contains

    subroutine init() 
      instance = c_init()
    end subroutine init

end module bridge

我的问题是我想在 init 中检查初始化。子程序,类似

subroutine init()
  if( instance .eq. c_null_ptr ) then
    instance = c_init()
  end if
end subroutine

但这给了我一个 Syntax error, found END-OF-STATEMENT when expecting one of: BLOCK BLOCKDATA PROGRAM MODULE TYPE INTEGER REAL COMPLEX BYTE CHARACTER CLASS后跟 This binary operation is invalid for this data type.
那么我应该改用什么?

最佳答案

您只需要使用 c_associated来自 iso_c_binding 的函数内在模块。它使用一个参数检查 null

subroutine init() 
  if( .not. c_associated(instance) ) then
    instance = c_init()
  end if
end subroutine init

关于fortran - 如何将 Fortran c_ptr 与 null 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32174843/

相关文章:

fortran - 宽度为零的格式描述符,如 F0.6 或 G0.8

c++ - Fortran COMPLEX 计算与 C++ 不同

python - f2py 函数释放 GIL

具有隐式类型的 Fortran SAVE 属性

c - Fortran-C 互操作性和 float 组

c++ - 在Visual Studio 2010中从Fortran调用C++函数

arrays - 用于调用 C 函数的 Fortran 接口(interface),该函数返回指向数组的指针

c - 通过 ISO_C_BINDING 传递 Fortran 数组

c - 将指针从 C 传递到 fortran 子例程

fortran - 格式语句中重复计数的扩展(与隐含的 do 循环结合)