c++ - Fortran调用C++指针函数

标签 c++ pointers fortran

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

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

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

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

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

谢谢!

最佳答案

正如 Ross 所评论的,您必须使 Fortran 接口(interface)返回 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)

关于c++ - Fortran调用C++指针函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32934775/

相关文章:

windows - Fortran 中的清屏

c++ - 我可以遍历 C++ 类的(公共(public))属性吗?

c - 为二维数组中的每一项存储一个值

c++ - 大 if else 语句

c - 使用指令 #define 定义指针 : need help to understand this piece of code

强制转换为 C99 中的指针数组

algorithm - 将 block 对角矩阵乘以向量的有效方法

fortran - 除以零时的无穷大符号

C++ 每秒运行一次异步函数

c++ - 在声明为返回unique_ptr <Base>的函数中返回unique_ptr <Derived>