簡體   English   中英

將Fortran整數數組僅傳遞給C子例程

[英]Passing Fortran integer array to C subroutine only first element passed

我試圖將一個整數數組從Fortran傳遞給C,但是我只能傳遞該數組的第一個元素。

我在下面的測試程序中會重現該錯誤。 我要去哪里錯了?

program test
   use foo

   integer (kind=c_int), allocatable :: hgmu_dose(:)
   allocate (hgmu_dose(0:10))

HGMU_dose(0)=22
HGMU_dose(1)=2
HGMU_dose(2)=3
HGMU_dose(3)=4
HGMU_dose(4)=5
HGMU_dose(5)=6
HGMU_dose(6)=7
HGMU_dose(7)=8
HGMU_dose(8)=9
HGMU_dose(9)=10
HGMU_dose(10)=11

print *, "HGMU_dose=", hgmu_dose 

call  test_interface(hgmu_dose)

end program

module foo
  use ISO_C_Binding 

  implicit none 
  interface  
    subroutine test_interface(dose) bind(C,name="INTERFACE")
      import :: c_int
      import :: c_double
      import :: c_char

      integer (kind=c_int), allocatable :: dose(:)
    end subroutine  
  end interface

end module foo 

#include "interface.h"

 namespace interface
{

  extern "C" void INTERFACE (int dose[NDIM])
  {
    for (int i = 0; i < NDIM; i++)
      cout << " dose[" << i << "] = " << dose[i] << endl;
  }
}

這里有幾個問題。

第一個是在test_interface接口的定義中。 您不需要或不需要allocatable關鍵字。

subroutine test_interface(dose) bind(C,name="INTERFACE")

  import :: c_int

  integer (kind=c_int) :: dose(:)

end subroutine

第二個是iso_c_binding將通過引用傳遞。 因此,當您使用C定義函數時,它應該接受指向數組的指針:

void INTERFACE (int *dose[NDIM])

最后,請注意,您不必將Fortran數組定義為從0開始。通常可以從1開始使用Fortran。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM