Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 36 ยท Systems and Tools

Interfacing with C

Call C from Ada and Ada from C: pragma Import, Export, Convention, Interfaces.C types, strings, callbacks and pointers, with runnable C stand-ins for the C side.

No real system is written in a single language. Operating systems expose C libraries, drivers come with C headers, and existing code is in C. Ada was designed for this: the standard defines how to import C functions, export Ada ones and exchange data with a predictable layout. You can add Ada's safety to a C code base one component at a time, or call the C library you already have.

The Ada examples are read-only on this site (no Ada compiler). The runnable parts are on the C side and show what the Ada binding calls.

Calling a C function from Ada

Suppose you want strlen from the C library, or your own int add (int a, int b). The standard package Interfaces.C defines Ada types that match C types: int, unsigned, long, double, char, size_t, and Interfaces.C.Strings handles char *.

ADA
with Interfaces.C; use Interfaces.C;

function C_Add (A, B : int) return int
  with Import        => True,
       Convention    => C,
       External_Name => "add";
  • Import => True says "the body is not here, it is in another language".
  • Convention => C selects the C calling convention.
  • External_Name is the linker symbol; without it the Ada name is used.

You call C_Add (2, 3) like any Ada function, and its parameters are type checked in Ada. The older form pragma Import (C, C_Add, "add"); means the same. Linking is done by naming the object file or library for the build tool, which the GNAT tools lesson covers.

Strings and pointers

C strings are null-terminated arrays of char. Ada's String is a bounds-carrying array, so conversion is needed:

ADA
with Interfaces.C.Strings; use Interfaces.C.Strings;

function C_Strlen (S : chars_ptr) return size_t
  with Import, Convention => C, External_Name => "strlen";

procedure Demo is
   P : chars_ptr := New_String ("hello");
begin
   Put_Line (size_t'Image (C_Strlen (P)));    --  5
   Free (P);
end Demo;

New_String allocates a C string; you must Free it. For simple input parameters you can use Interfaces.C.To_C ("text"), which returns a char_array ending in a null, and pass its address. For anything where the C side keeps the pointer, make sure the memory outlives the call.

Pass-by-reference records and arrays work when you use the C convention on the type: type Point is record X, Y : int; end record with Convention => C; matches struct { int x, y; }.

Bridging two worlds

Import call C from Ada
Export call Ada from C
Convention C same layout and calls
Interfaces.C matching types

You own the memory across the boundary.

1 / 2

Calling Ada from C

Export an Ada subprogram with the same aspects the other way round:

ADA
function Clamp (X, Lo, Hi : Interfaces.C.int) return Interfaces.C.int
  with Export, Convention => C, External_Name => "ada_clamp";

function Clamp (X, Lo, Hi : Interfaces.C.int) return Interfaces.C.int is
  (if X < Lo then Lo elsif X > Hi then Hi else X);

In C you declare int ada_clamp(int, int, int); and call it. If the Ada side is a library and the main program is in C, the Ada runtime must be initialized first (GNAT's stand-alone library feature generates an ...init function for this), and finalized at the end.

Callbacks

C libraries often take function pointers (qsort's comparator, signal handlers, GUI events). In Ada, give a subprogram the C convention and pass 'Access to it:

ADA
type Compare_Fn is access function (A, B : System.Address) return int
  with Convention => C;

function Compare_Ints (A, B : System.Address) return int
  with Convention => C;

Keep callbacks short and never let an Ada exception escape into C: C does not know about them, so catch everything inside the callback and return an error value.

Safety at the boundary

The boundary is where Ada's guarantees stop. C will not check ranges or lengths, so validate inputs before calling out, and wrap imported functions in a small Ada package with proper types and contracts. Then the rest of your program uses safe Ada and only the thin wrapper touches raw pointers. In SPARK, imported subprograms are specified with contracts you promise are correct, since the tool cannot see C code.

Stand-in: the C side of a binding (C, runnable)

This program contains the C functions a binding would import (add, a string length, an ada_clamp lookalike) and calls them directly. When you write the real Ada binding, the signatures here are what Interfaces.C types must match.

C C stand-in: the library an Ada binding would import

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: a callback with a C function pointer (C, runnable)

qsort with a comparator is the textbook C callback. In Ada you would import qsort and pass an Ada function with Convention => C. Note how the callback must be total and never throw.

C C stand-in: qsort with a comparator callback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output is -3 7 7 19 42 100.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which aspects declare a subprogram implemented in C?

    Import says the body is elsewhere and Convention selects the calling convention.
  2. 2. Which package provides Ada types matching C's int and char?

    Interfaces.C defines int, unsigned, double, char, size_t and friends.
  3. 3. What should never happen inside a callback called by C?

    C cannot handle Ada exceptions; catch everything inside the callback.
  4. 4. Who must free a C string made with New_String?

    New_String allocates memory outside Ada's automatic management.

Summary

  • Import/Export aspects with Convention => C connect Ada and C.
  • Interfaces.C and Interfaces.C.Strings supply matching types and string conversion.
  • Records and arrays with C convention share layout with C structs and arrays.
  • Callbacks need the C convention and must not let exceptions escape.
  • Wrap imported code in a thin, well-typed Ada layer and validate inputs at the boundary.

Next: GNAT, GPRbuild and Alire