【问题标题】:Fortran calls C++ pointer functionFortran 调用 C++ 指针函数
【发布时间】:2016-01-01 07:02:40
【问题描述】:

我在将 Fortran 程序与 C++ 函数连接时遇到问题。 我的任务是从fortran调用C++函数指针,例如:

// C++ function pointer
double* GetSplinePtr()
{
    return sp;
}

我使用 iso_c_binding 程序和 fortran 接口。 对于非指针函数,我通常使用这个声明:

real(kind=c_double) function Name(x,y) bind(c, name='Name')
use iso_c_binding
implicit none
real(c_double), intent(in), value :: x,y
end function Name

但是对于返回指针的函数我应该使用什么?

谢谢!

【问题讨论】:

  • C_PTR这个类型呢,也是模块iso_c_binding的一个组件?
  • 您确定intent(in)value 可以同时使用吗?
  • @vladimirf intent(inout)intent(out) 肯定与 value 冲突,但与 intent(in) 不冲突?
  • 是的,我记错了约束,它是(F2008):C558 An entity with the VALUE attribute shall not have the ALLOCATABLE, INTENT (INOUT), INTENT (OUT), POINTER, or VOLATILE attributes.
  • 它是 C 还是 C++ 指针?如果它是 C++ 指针,则存在名称修饰。它应该在 C++ 端声明为 extern "C" 以避免名称混乱。

标签: c++ pointers fortran


【解决方案1】:

作为 Ross cmets,您必须制作 Fortran 接口以返回 C 指针并自己转换为 Fortran 指针。

interface
  function GetSplinePtr() result(res) bind(C, name="GetSplinePtr")
    use iso_c_binding
    type(C_ptr) :: res
  end function
end interface

在调用代码中,您必须从iso_c_binding 模块调用c_f_pointer()

  use iso_c_binding

  type(c_ptr) :: p
  real(c_double), pointer :: x

  p = GetSplinePtr()

  call c_f_pointer(p, x)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 2011-01-29
    • 2014-07-24
    相关资源
    最近更新 更多