j3-fortran / fortran_proposals

Proposals for the Fortran Standard Committee
175 stars 14 forks source link

C_loc for polymorphic types #300

Open foxtran opened 1 year ago

foxtran commented 1 year ago

Dear all,

Currently, c_loc does not work with polymorphic types. For example, in the case of GCC:

  type(c_ptr) function class_get_addr_1(data) result(data_ptr)
    class(*), target, intent(in) :: data(*)
    data_ptr = c_loc(data)
  end function class_get_addr_1

the error is:

    6 |     data_ptr = c_loc(data)
Error: X argument at (1) to C_LOC shall not be polymorphic

However, with a small trick, it can work:

  type(c_ptr) function class_get_addr_2(data) result(data_ptr)
    type(*), intent(in) :: data(*)
    data_ptr = type_get_addr(data)
  end function class_get_addr_2
  type(c_ptr) function type_get_addr(data) result(data_ptr)
    type(*), target, intent(in) :: data(*)
    data_ptr = c_loc(data)
  end function type_get_addr

So, polymorphism was removed by calling type_get_addr, and, therefore, the address was got. After that, I did not get why c_loc can not work with polymorphic types.