Building C library interfaces with ISO_C_BINDING

Building C library interfaces with ISO_C_BINDING

I have been experimenting with building Fortran interfaces to C library functions. Here are some of my ideas. It would be good to hear what other people think.

In general, a good C interface should have wrapper functions to deal with string conversions, so the library user doesn't have to pass arguments like "TRIM(STRING)//C_NULL_CHAR". I put together a few routines to do string conversions, which works well except for the case of variable-length result strings. In this case, it may be good to have one version that uses ISO_VARYING_STRING, and one that doesn't. I think F2008 includes string length as an allocation parameter, so this problem will go away.

To make more specific INTERFACE specifications, I have made aliases for all of the unsigned integer types, and for C_PTR types, such as:
use, intrinsic :: ISO_C_Binding, &
C_ptr => C_ptr , &
C_char_ptr => C_ptr, &
C_void_ptr => C_ptr, &
C_int => C_int, &
C_unsigned_int => C_int, &

Likewise, a C function typedef can have an alias for C_FUNPTR. The are not distinct as far as the compiler is concerned, but they help make the code easier to understand.

Sometimes, it is better if pointers really are different, so that different C pointer types can be distinct for a set of generic procedures. In this case, a derived type can be made that is an opaque container for a TYPE(C_PTR), with Fortran wrapper functions that pass the generic C pointer to the specific C routine. This makes it possible to do a fairly accurate Fortan interface to a C++ class, where the first Fortran argument is an object pointer. One caveat is that Fortran has a silly rule that functions and subroutines cannot share the same generic name. Of course, interfacing C++ also needs C wrapper functions to make the actual C++ calls.

One problem with automatic header generation is that C headers are not very precise. Arrays and pointer notation are generally interchangeable, so you cannot distinguish an array argument from a scalar pass-by-address. I was looking at Microsoft's SAL annotation. They seem to have designed it for interfacing to languages like C#, and it would also be a big help for generating automatic Fortran interfaces. If something like SAL became standard, it would be a big help to a lot of languages that interface with C libraries.

1 post / 0 new
For more complete information about compiler optimizations, see our Optimization Notice.