Generating Function Prototypes

Alastair Reid reid at reid-consulting-uk.ltd.uk
Wed Jul 3 11:34:04 EDT 2002


> The "proper" way to do it is to write the prototype yourself in a C
> header file (or use an existing header), and then use a
> compiler-specific mechanism to #include it.

Shouldn't we encourage people to use the compiler-independent
mechanism instead (and exclusively)?

That is, you put all your flags, includes, prototypes, etc. into a 
header file:

  foo.h:
    #include "config.h"
    #define ENABLE_FEATURE_X
    #include <X11/Xlib.h>
    #ifdef HAVE_STDLIB_H
    #include <stdlib.h>
    #endif
    
    extern void my_helper_function(int x) {...}

and then mention foo.h in all relevant foreign imports:

  Foo.hs:
    ...
    foreign import "foo.h" x :: ...
    foreign import "foo.h" y :: ...
    foreign import "foo.h" z :: ...
    foreign import "foo.h" my_helper_function :: ...

Using this approach is easier for users and easier for tools which
generate ffi output.  (I recently modified the ffi backend of
GreenCard to generate code like this instead of using the GHC-specific
mechanism SimonM described.)

They still have to use compiler-specific mechanisms to specify
#include search paths, linker options, etc.

> The nhc98 compiler does generate a prototype (ghc does not).
> However, although this works quite well in the general case,
> occasionally the generated prototype may not be compatible with the
> real C type of the function (e.g. it cannot guess the `const'
> attribute).

In a sense though, this doesn't matter because C compilers use the
same calling conventions for const arguments and non-const arguments.
Likewise, all compilers we know of pass data pointers around the same
way no matter what the size and alignment of the thing they point at.
(And if either of these properties is found to change, I believe we
would change the ffi so that it is still feasible to generate correct
machine code without being given a function prototype by the user.)

Of course, this ignores the detail that while the C compilers are
generating correct code, they may also be generating warnings about
alleged type errors - which can be a bit disconcerting.

-- 
Alastair Reid        reid at cs.utah.edu        http://www.cs.utah.edu/~reid/




More information about the FFI mailing list