0

I'm trying to bridge some C code into Fortran. However, I'm having trouble getting the variable length C strings returned by the C API into the fixed length strings required by the Fortran API.

Here's a reduced version of the code that won't compile - I get 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 is just the module containing the c_bridge_getValue() and c_bridge_releaseString definitions, and the bridge pointer (just a void*)

c_bridge_getValue() just mallocs up a new string and returns it, and c_bridge_releaseString() frees the memory.

So my question is, what do I need to do to assign the string variable to the getValueFromC?

1
  • 1
    Always use tag fortran for Fortran questions. And your code is Fortran2003, so the fortran90 tag was inappropriate. Commented Mar 8, 2016 at 9:30

1 Answer 1

1

One solution is to loop and assign to the string slices. I've not verified that this is 100% right, but it compiles for me...

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
Sign up to request clarification or add additional context in comments.

2 Comments

That is correct, the problem is that getValueFromC is a character string (scalar) and string is an array of characters of length 1.
Yes, I'd say this is a valid solution, I am doing the same: bitbucket.org/apesteam/aotus/src/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.