使用 Fortran 中的 **int 参数调用 C 函数

Doo*_*ggy 5 c fortran fortran-iso-c-binding

假设我有一个带有以下 API 的 C 函数:

int c_function(int **a);
Run Code Online (Sandbox Code Playgroud)

假设 C 函数负责内存分配,我应该如何声明 Fortran 数组/指向数组的指针,并将其传递给函数?

Vla*_*r F 4

您必须声明一个 Fortan c 指针type(c_ptr)

type(c_ptr) :: ptr
Run Code Online (Sandbox Code Playgroud)

然后调用你的函数(使用适当的接口)

n = c_function(ptr)
Run Code Online (Sandbox Code Playgroud)

然后才将 Fortran 数组指针指向那里

real, pointer :: Array(:)

call c_f_pointer(ptr, Array, [n])
Run Code Online (Sandbox Code Playgroud)

我假设这n是数组的大小。你必须知道这一点,否则这是不可能的。

界面可能看起来像

interface

    integer(c_int) function c_function(ptr) bind(C,name="c_function")
      use iso_c_binding
      type(c_ptr) :: ptr
    end function

end interface
Run Code Online (Sandbox Code Playgroud)