Enumerator type in `bind(c)` derived type: best practice?

I am writing an interface to a C code that has simple structures with enumerated variables, like:

typedef enum {one, two, three} number_t;

typedef struct {
   number_t a
} color_code;

What’s the best practice - i.e. how to render the code in the cleanest way - to bind this type to a Fortran derived type? So far I think using integer parameters works better than using Fortran enums:

! Get C enum integer kind
enum, bind(C); enumerator :: c_enum_0; end enum
integer, parameter :: c_enum = kind(c_enum_0)

! Enumerate with integers
integer, parameter :: number_t = c_enum
integer(number_t), parameter :: one = 0
integer(number_t), parameter :: two = 1
integer(number_t), parameter :: three = 2

! Bind structure
type, bind(C) :: color_code
   integer(number_t) :: a
end type

Note I’m not wondering about potential improvements to the language here, but just trying to understand what’s the best way to deal with them with what the standard offers today.

My suggestion and my own practice will be to use the Fortran 2023 enum type feature:

..
enum, bind(C) :: number_t
   enumerator :: one, two, three
end type
..
type(number_t) :: number
..
number = two

This is not perfect but I will make do with it, especially in the context of intereoperability with C in Fortran.

2 Likes

That syntax will be absolutely spot on when it’s more or less universally supported!

With open-source compilers such as gfortran and LFortran (@certik), Fortranners can start working on providing the support now and make it happen before the ink is dry on the Fortran 2023 standard publication.

Honestly when Fortran Discourse kicked off a couple of years ago, I must admit my expectation was about half a dozen Fortranners globally, who would become regular readers of this site, will also get into development work for GCC and become gfortran volunteers, been disappointed that has not happened.

If readers (i.e., primary users of non-commercial Fortran processors who happen to be not in industry e.g., academia or public research, etc.) can somehow be encouraged to contribute, gfortran can be the leading fully standard-conformant processor out there with the first to get new standard facilities such as Fortran 2022 enum types implemented.

2 Likes

If anybody is interested in implementing this in LFortran, I will be happy to mentor you and even find funding. Please get in touch with me.

1 Like