将字符串数组从Fortran传递到C / C ++ DLL并获取具有更改值的数组

时间:2017-12-13 09:25:48

标签: c++ c dll fortran fortran-iso-c-binding

我正在创建一个接受int doubleijk_(char* data[]) // what should be the return type ??? { // code to change array elements return 0; } (String数组)的C / C ++ DLL,更改数组中的值并返回。

我的C / C ++实现:

module variables
  type string
    character(len=:), allocatable :: str
  end type string
end module variables


program Call_CPP
    use variables
    type(string) :: array(3) 
    array = [string('xyza'), string('abcd'), string('mnopqrs')]

    INTERFACE
! How to write SUBROUTINE for array

       SUBROUTINE doubleijk_(arr) BIND(C,NAME='doubleijk_')

!???????WHAT SHOULD BE SUBROUTINE FOR ARRAY OF STRINGS????????

       END SUBROUTINE doubleijk_

    END INTERFACE

    ! Body of Call_CPP

    call doubleijk_(array)

 ! print values of array after call

    end program Call_CPP

在Fortran中(使用ifort)我正在调用DLL的函数:

p <- plot_ly(
    x = missing_data$bucket,
    y = missing_data$key,
    z = missing_data$count,
    type = "heatmap") %>%
    layout(
        xaxis = list(type = "category", tickangle = 0, tick0 = 10, dtick = 10),
        yaxis = list(type = "category", size = 3, tickwidth = 0, ticklen = 0.1, size = 15),
        margin = list(l = 150, r = 50, b = 50, t = 50, pad = 4))
p

我能够从Fortran传递字符串,整数并从C / C ++中获得更改值。我需要的是将字符串数组从Fortran传递到C / C ++并使用更改的值返回数组。我该怎么做?

1 个答案:

答案 0 :(得分:0)

终于做到了。这是解决方案。

 program Call_CPP
 use iso_c_binding, only: c_associated, c_loc, c_ptr

    INTERFACE
       SUBROUTINE doubleijk_(stringPtrs) BIND(C,NAME='doubleijk_')
        use iso_c_binding      
        TYPE(C_PTR), DIMENSION(3) :: stringPtrs

       END SUBROUTINE doubleijk_

    END INTERFACE

    TYPE(C_PTR), DIMENSION(3) :: stringPtr
    CHARACTER(LEN=20), DIMENSION(3), TARGET :: stringArray
       DO ns = 1, 3
           stringArray(ns) = "My String"//char(0)
           stringPtr(ns) = c_loc(stringArray(ns))
       END DO

    ! Body of Call_CPP

    call doubleijk_(stringPtr) !Call C function

     DO ns = 1, 3
            print *, stringArray(ns) !print array after call-changed values
     END DO

    end program Call_CPP