Search code examples
fortrangtkgtk3gobject

how to convert a gchar to a fortran character?


I am using the combo box with text in GTK fortran in VS community 2019 solution. I am trying to get the string selected with "gtk_combo_box_text_get_active_text" and c_f_pointer to convert the gchar back to fortran character. It will work fine if something is selected and not null. When it is null I will receive a crash as follows: crash

I guess this is because the pointer is pointing to null and cannot be accessed, but it would be best if I can also detect nothing is selected.

Thus, I would like to ask if there is a better and also simple way to convert the gchar to fortran character OR a way to detect it being null without crashing it. Thank you everyone!

These are the code I am dealing with:

botMain_systemChoosing = gtk_combo_box_text_new()
call gtk_container_add(bottomPanel_Main,botMain_systemChoosing)
call gtk_combo_box_text_append(botMain_systemChoosing,"1","system 1")
call gtk_combo_box_text_append(botMain_systemChoosing,"2","system 2")
call gtk_widget_show(botMain_systemChoosing)

.....

type(c_ptr) :: currentSys
character(len=8),pointer :: string
currentSys = gtk_combo_box_text_get_active_text(botMain_systemChoosing)
call c_f_pointer(currentSys,string)
if (string == "system 1") then
    print*, "1"
else 
    print*, "default"
end if 

EDIT solution#1:

use, intrinsic :: iso_c_binding, only: c_ptr,c_associated

type(c_ptr) :: currentSys
character(len=8),pointer :: string
// returns a gchar
currentSys = gtk_combo_box_text_get_active_text(botMain_systemChoosing) 
call c_f_pointer(currentSys,string)
if (.not. c_associated(currentSys)) then 
    print*, "null"
elseif (string == "system 1") then
    print*, "1"
else 
    print*, "default"
end if

Solution

  • I don’t have experience with gtk-fortran, but I guess you should just check that the pointer is associated:

    if (.not.associated(string)) then 
        print*, “null”
    elseif (string == "system 1") then
        print*, "1"
    else 
        print*, "default"
    end if
    

    See this example:

    program test_ptr
            use iso_c_binding
            implicit none
    
            type(c_ptr) :: c = c_null_ptr
            character(kind=c_char,len=1), pointer :: s(:)
    
            call c_f_pointer(c,s,[10])
    
            print *, 'fortran associated = ',associated(s),' c associated=',c_associated(c)
    
    end program
    

    it prints

     fortran associated =  F  c associated= F