将变长字符串分配给固定长度字符串

时间:2016-03-08 08:38:59

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

我试图将一些C代码桥接到Fortran中。但是,我无法将C API返回的可变长度C字符串转换为Fortran API所需的固定长度字符串。

这是一个不会编译的代码的简化版本 - 我得到了The shapes of the array expressions do not conform

character*200 function getValueFromC() 
  use cbridge
  implicit none

  type(c_ptr) :: resultString
  integer(kind=c_int) :: resultLength
  character, pointer, dimension(:) :: string

  call c_bridge_getValue(bridge, resultString, resultLength)
  call c_f_pointer(resultString, string, (/ resultLength /) )
  getValueFromC = string
  call c_bridge_releaseString(resultString)
end function getValueFromC

cbridge只是包含c_bridge_getValue()c_bridge_releaseString定义的模块,以及bridge指针(只是void*

c_bridge_getValue()只需malloc新的字符串并将其返回,c_bridge_releaseString() free为内存。

所以我的问题是,如何将string变量分配给getValueFromC

1 个答案:

答案 0 :(得分:1)

一种解决方案是循环并分配给字符串切片。我没有证实这是100%正确,但它为我编译......

character*200 function getValueFromC() 
  use cbridge
  implicit none

  type(c_ptr) :: resultString
  integer(kind=c_int) :: resultLength
  character, pointer, dimension(:) :: string

  call c_bridge_getValue(bridge, resultString, resultLength)
  call c_f_pointer(resultString, string, (/ resultLength /) )
  do i = 1, min(200, resultLength)
    getValueFromC(i:i) = string(i)
  end do
  call c_bridge_releaseString(resultString)
end function getValueFromC