ComIn 0.5.1
ICON Community Interface
Loading...
Searching...
No Matches
comin_c_utils.F90
Go to the documentation of this file.
1!> @file comin_c_utils.F90
2!! @brief ComIn C utilities, contains helper routines for converting data
3!! between C and Fortran.
4!
5! @authors 01/2023 :: ICON Community Interface <comin@icon-model.org>
6!
7! SPDX-License-Identifier: BSD-3-Clause
8!
9! See LICENSES for license information.
10! Where software is supplied by third parties, it is indicated in the
11! headers of the routines.
12!
14
15 use, INTRINSIC :: iso_c_binding, only: c_ptr, c_char, c_f_pointer, c_null_char, c_size_t
16 IMPLICIT NONE
17
18 PRIVATE
20
22 MODULE PROCEDURE convert_c_string_cptr
23 MODULE PROCEDURE convert_c_string_arr
24 END INTERFACE convert_c_string
25
26CONTAINS
27
28 !> Convert c-style character array into Fortran string.
29 !
30 FUNCTION convert_c_string_cptr( cptr ) RESULT (string)
31 TYPE(c_ptr), intent(in) :: cptr
32 CHARACTER(len=:), allocatable :: string
33
34 INTEGER(c_size_t) :: len
35 CHARACTER(kind=c_char), POINTER :: chars(:)
36 INTEGER(c_size_t) :: i
37
38 INTERFACE
39 FUNCTION c_strlen(str_ptr) BIND ( C, name = "strlen" ) RESULT(len)
40 IMPORT :: c_ptr, c_size_t
41 TYPE(c_ptr), VALUE :: str_ptr
42 INTEGER(kind=c_size_t) :: len
43 END FUNCTION c_strlen
44 END INTERFACE
45
46 len = c_strlen(cptr)
47
48 CALL c_f_pointer(cptr, chars, [ len ])
49
50 ALLOCATE(CHARACTER(len=len) :: string)
51 DO i=1,len
52 string(i:i) = chars(i)
53 END DO
54 END FUNCTION convert_c_string_cptr
55
56 FUNCTION convert_c_string_arr( arr ) RESULT (string)
57 CHARACTER(kind=c_char), INTENT(IN) :: arr(:)
58 CHARACTER(len=:), ALLOCATABLE :: string
59 INTEGER :: i, strlen
60
61 DO strlen=1,SIZE(arr)
62 IF (arr(strlen) .EQ. c_null_char) EXIT
63 END DO
64
65 ALLOCATE(CHARACTER(len=strlen-1) :: string)
66 DO i=1,strlen-1
67 string(i:i) = arr(i)
68 END DO
69 END FUNCTION convert_c_string_arr
70
71 !> Convert Fortran string into C-style character array.
72 !
73 subroutine convert_f_string( string, arr)
74
75 CHARACTER(len=*), INTENT(IN) :: string
76 CHARACTER(len=1, kind=c_char), INTENT(INOUT) :: arr(:)
77 INTEGER :: i
78
79 DO i=1,len_trim(string)
80 arr(i) = string(i:i)
81 END DO
82 arr(i) = c_null_char
83 end subroutine convert_f_string
84
85END MODULE comin_c_utils
subroutine, public convert_f_string(string, arr)
Convert Fortran string into C-style character array.