c - 将字符串数组从 C 返回到 Fortran

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

我正在尝试使用“iso_c_binding”将一个字符串数组从 C 返回到 Fortran。该程序编译,但给出一个运行时错误。
我的 C 程序:

#include <stdio.h>    
void ret_array(int * numStrings, char **arr2 ) {                                
    int dim1=5;    
    char *arr1[5]={"name1","name2","name3","name4","name5"};    
    arr2 = &arr1;    
    printf("%s\n",arr2[0]);    
    printf("%s\n",arr2[1]);    
    printf("%s\n",arr2[2]);    
    printf("%s\n",arr2[3]);    
    printf("%s\n",arr2[4]);    
    numStrings = &dim1;    
    printf("%s","Ending  interface :");    
    fflush(stdout);    
 }  
我的调用 Fortran 程序
program main
  implicit none
  CHARACTER(LEN = 255), dimension(:), allocatable:: str2
  integer(kind = 4):: istr
  call get_arr(istr, str2)
  PRINT *, str2(1)
contains
  subroutine get_arr(n, str1)
    use iso_c_binding
    implicit none
    INTEGER(KIND = 4):: n
    CHARACTER(LEN = 255), dimension(:), ALLOCATABLE:: str1
    character(kind = c_char), pointer:: fptr(:)
    TYPE(C_PTR), DIMENSION(:), allocatable:: cptr
    integer:: len1, ii

    interface 
      subroutine ret_array(dim_len, str_arr1) bind(c)
        use iso_c_binding
        integer(c_int), INTENT(OUT):: dim_len
        TYPE(C_PTR), DIMENSION(:,:), intent(out):: str_arr1
      end subroutine
    end interface

    call ret_array(n, cptr)
    PRINT *,"Number :",n
    allocate(str1(n))
    do ii = 1, n
      call c_f_pointer(cptr(ii), fptr, [ 255 ])
      len1 = index(fptr(ii), C_NULL_CHAR)
      PRINT *,len1
      str1(ii) = TRANSFER(fptr(1:len1-1),  str1(ii))
    end do
  end subroutine
end program                    
当我运行它时,出现以下错误。
name1
name2
name3
name4
name5
Ending  interface :
Program received signal SIGFPE: Floating-point exception - erroneous arithmetic operation.

Backtrace for this error:
#0  0x7f9e86776d01 in ???
#1  0x7f9e86775ed5 in ???
#2  0x7f9e865aa20f in ???
#3  0x7f9e869aa077 in ???
#4  0x55e9a5195350 in get_arr
    at /home/test/fort_code/ret_arr.f90:27
#5  0x55e9a5195984 in MAIN__
    at /home/test/fort_code/ret_arr.f90:6
#6  0x55e9a5195a37 in main
    at /home/test/fort_code/ret_arr.f90:7
make: *** [Makefile:3: run] Floating point exception (core dumped)
我是在 iso_c_binding 中使用指针的新手。你能指出为什么指针没有被返回给 Fortran 程序吗?
在此先感谢您的帮助

最佳答案

您正在更改 arr2指向本地数组 arr1然后返回本地数组的地址。
那行不通。 arr1函数返回后无效。

关于c - 将字符串数组从 C 返回到 Fortran,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68076543/

相关文章:

在 pthread 中计算 pi

基于C的conf文件阅读器

C - 从文件读取 - 为什么打印错误?

C : Accessing contiguous array elements using a pointer returned by a function

c++ - 为什么 "struct with const member"类型的指针不能指向 "struct with non-const member"?

arrays - 在 Fortran 中将指针分配给可分配的派生类型组件

c# - 尾数介于 0 和 1 之间的科学计数法的 .NET 格式说明符

c - msgrcv() 中的错误 :receiving data through message queue in C

C 指向数组的 union 指针

garbage-collection - fortran 有垃圾收集器(gc)吗?