2016-03-08 156 views
0

我试图将一些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 s上行一个新的字符串并返回它,c_bridge_releaseString()free S上的存储器。

所以我的问题是,我需要做些什么来将string变量分配给getValueFromC

+1

总是使用标签fortran的Fortran问题。而你的代码是Fortran2003,所以fortran90标签是不合适的。 –

回答

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 
+0

这是正确的,问题是'getValueFromC'是一个字符串(标量),'string'是一个长度为1的字符数组。 –

+0

是的,我会说这是一个有效的解决方案,我正在做同样的:https://bitbucket.org/apesteam/aotus/src/c2aafc4d76bafad7115867a6a0cd93406552a0a0/source/aot_top_module.f90?at=default&fileviewer=file-view-default#aot_top_module.f90-282 – haraldkl

相关问题