c++ - 为什么这种将指针从 C++ 传递到 Fortran 的尝试不起作用?

标签 c++ pointers fortran fortran-iso-c-binding

我需要将动态数组从 C++ 传递到 Fortran。我做了很多研究来组合一个我认为应该有效的例子,但事实并非如此。该程序应该在 c++ 程序中创建一个数组,将该数组的指针传递给 Fortran 例程,将 C 指针转换为 Fortran 指针,然后在 Fortran 端打印该数组。

我的 C++ 主程序:

using namespace std;

extern "C" {
   void cinterface(int*,int*);
}

int main()
{
   int carray[]={0,1,2,3,4};
   int carray_siz=5;

   cinterface(&carray_siz,carray);

   return 0;
}

我的 Fortran 例程:

module fortmod

   use ISO_C_BINDING

   implicit none

contains

   subroutine cinterface(carray_siz,carray_ptr) bind(C)

      implicit none

      integer(c_int), intent(in) :: carray_siz
      type(c_ptr), intent(in) :: carray_ptr

      integer(c_int), pointer :: pfarray(:) => NULL()

      call C_F_POINTER(carray_ptr,pfarray,[carray_siz])

      print *, pfarray

   end subroutine cinterface

end module fortmod

我将其构建为:

gfortran -c fortmod.f90
g++ main.cpp fortmod.o -lgfortran

但是当我运行它时,它没有打印数组值,而是说:

Segmentation fault (core dumped)

我对指针的概念还很陌生,所以我想我不明白它们是如何正确工作的。您能否指出为什么我在运行此程序时会出现此内存错误?

最佳答案

您当然希望将数组大小作为 int 传递,而不是大小的地址:

extern "C" {
    void cinterface(int,int*);
}

cinterface(carray_siz,carray);

关于c++ - 为什么这种将指针从 C++ 传递到 Fortran 的尝试不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20249808/

相关文章:

c++ - 编译 GCC 时错误部分模板特化,但不是 MSVC

c - 为C中结构体中定义的字符指针分配静态内存

fortran - 创建要在消息记录中使用的重载函数

makefile - 使用 Makefile 编译 F90 时出错

floating-point - 比较浮点加法的存储结果与 Fortran 中的临时结果

c++ - 通过纹理四边形的 OpenGL 字体

c++ - 使用 C/C++ (GCC/G++) 在 Linux 中的套接字编程中发送和接收文件

c++ - 在 C++ 中如何为结构类型分配内存

c - 双指针段错误

c - 为什么 C 中的 realloc() 会改变内存?