2016-03-08 134 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