Created
June 10, 2020 11:57
-
-
Save ivan-pi/e980c22d275db69226a3fea75f994e37 to your computer and use it in GitHub Desktop.
See discussion at https://fortran-lang.discourse.group/t/best-practices-for-passing-c-strings/104/12
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
subroutine C_F_STRPOINTER (STRARRAY, FSTRPTR, MAXLEN) | |
use, intrinsic :: ISO_C_BINDING | |
implicit none | |
character, dimension(*), target, intent(in) :: STRARRAY | |
character(:), pointer, intent(out) :: FSTRPTR | |
integer, intent(in), optional :: MAXLEN | |
integer :: curlen | |
curlen = 0 | |
do | |
curlen = curlen +1 | |
if (PRESENT(MAXLEN)) THEN | |
if (curlen > MAXLEN) exit | |
end if | |
if (STRARRAY(CURLEN) == CHAR(0)) exit | |
end do | |
call doassign(C_LOC(STRARRAY), FSTRPTR, curlen-1) | |
contains | |
subroutine doassign(CSTRPTR, FSTRPTR, STRLEN) | |
type(C_PTR), intent(in) :: CSTRPTR | |
character(:), pointer, intent(out) :: FSTRPTR | |
integer, intent(in) :: STRLEN | |
character(STRLEN), pointer :: p | |
call C_F_POINTER(CSTRPTR, p) | |
FSTRPTR => p | |
return | |
end subroutine doassign | |
end subroutine C_F_STRPOINTER | |
function f_c_string(string,trim) | |
use, intrinsic :: iso_c_binding, only: c_char,c_null_char | |
character(len=*), intent(in) :: string | |
logical, intent(in), optional :: trim | |
character(kind=c_char,len=:), allocatable :: f_c_string | |
logical :: trim_ | |
trim_ = .true. | |
if (present(trim)) trim_ = trim | |
block | |
intrinsic trim | |
if (trim_) then | |
f_c_string = trim(string)//c_null_char | |
else | |
f_c_string = string//c_null_char | |
end if | |
end block | |
end function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment