我正在尝试将一些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
?
一种解决方案是循环并分配给字符串切片。我尚未验证这是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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句