我试图将一些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
?
答案 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