I need to convert a C string to a Fortran string. When I debug the example code, in Visual Studio 2012 with the Intel Visual Fortran Composer XE 2013, I encounter a couple of issues:
1) I can't see the value of the deferred-length allocatable character variable (str) in the debugger.
2) Allocating this variable type causes the fCode.pdb file to lock when a break point is placed in the code. The only way to free the file is to close the handle (via Process Explorer) or close the IDE.
Am I missing something in the code? Freeing memory? Is there a cleaner way to do the conversion?
C code
int main ( void ) {
char* cstr = "BP1000";
c_to_f(cstr);
return 0;
}
Fortran code
module mytest
contains
subroutine c_to_f(cstr) BIND(C, name="c_to_f")
use, intrinsic :: iso_c_binding
!DEC$ ATTRIBUTES DLLEXPORT :: c_to_f
character(kind=C_CHAR, len=1), intent(IN) :: cstr(*)
character(:), allocatable :: str
str = c_to_f_string(cstr)
end subroutine c_to_f
function c_to_f_string(s) result(str)
use, intrinsic :: iso_c_binding
character(kind=C_CHAR, len=1), intent(IN) :: s(*)
character(:), allocatable :: str
integer i, nchars
i = 1
do
if (s(i) == c_null_char) exit
i = i + 1
end do
nchars = i - 1 ! Exclude null character from Fortran string
allocate(character(len=nchars) :: str)
str = transfer(s(1:nchars), str)
end function c_to_f_string
end module mytest