2014-11-21 19 views
0

我將一些由C函數讀入的數據傳遞給一個將執行所有數字運算的Fortran程序。該陣列在Fortran中自然被視爲具有形狀(2, nn)。由於C沒有多維數組,所以在C中分配和使用數組,長度爲2 * nnfortran不用臨時數組重新整形

我想重塑Fortran中的數組,以便在數字代碼中使用方便的索引。在Fortran例程會是這個樣子:

subroutine fortran_glue_code(n, array) bind(c) 
    use iso_c_binding, only: c_int 
    integer(c_int), intent(in) :: n, array(2 * n) 
    real(double_precision) :: result 

    call do_the_number_crunching(result, reshape(array, [2, n])) 
    { do stuff with the result... } 
end subroutine 

subroutine do_the_number_crunching(result, array) ! not C-interoperable 
    real(double_precision), intent(out) :: result 
    integer, intent(in) :: array(:,:) 

    if (size(array, 1) /= 2) then 
     print *, "Wrong size!" 
     call exit(1) 
    end if 

    { crunch crunch crunch... } 
end subroutine 

我不開心是什麼reshape不必要創建一個臨時數組,並與數據我會使用,在一個非常大的一個。

有問題的程序將array視爲只讀,因此我認爲,編譯器可以簡單地創建一個新的Fortran陣列頭,該頭指向陣列內容的相同內存位置,只是不同的尺寸。有沒有什麼辦法可以避免重構陣列的副本?

回答

3

我不明白你的問題,你爲什麼不只是做

subroutine fortran_glue_code(n, array) bind(c) 
    use iso_c_binding, only: c_int 
    integer(c_int), intent(in) :: n, array(2, n) 
    real(double_precision) :: result 

    call do_the_number_crunching(result, array) 
    { do stuff with the result... } 
end subroutine 

另外,您也可以使用序列關聯

subroutine fortran_glue_code(n, array) bind(c) 
    use iso_c_binding, only: c_int 
    integer(c_int), intent(in) :: n, array(2 * n) 
    real(double_precision) :: result 

    call do_the_number_crunching(result, array, n) 
    { do stuff with the result... } 
end subroutine 

subroutine do_the_number_crunching(result, array, n) ! not C-interoperable 
    real(double_precision), intent(out) :: result 
    integer, intent(in) :: array(2,n) 
    integer, intent(in) :: n 

    if (size(array, 1) /= 2) then 
     print *, "Wrong size!" 
     call exit(1) 
    end if 

    { crunch crunch crunch... } 
end subroutine 

但這是不必要的併發症。

+0

啊我想''數組''只能在膠水代碼中爲一些愚蠢的原因或其他的大小'2 * n',但這是有道理的。 – korrok 2014-11-23 17:04:29

0

如果在Fortran在C代碼中使用int **,然後type (c_ptr),可以使用固有子程序c_f_pointer到C-指針與指針屬性的Fortran數組相關聯,指定的Fortran數組的維數與所述第三個參數c_f_pointer。猜測,在我看來,編譯器不需要執行副本,而是使用C指針地址來創建Fortran指針/結構來定位數據。