Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #190 Call an external C function

Declare an external C function with the prototype

void foo(double *a, int n);

and call it, passing an array (or a list) of size 10 to a and 10 to n.

Use only standard features of your language.

with Interfaces.C;
procedure C_Foo (A : access Interfaces.C.double;
                 N : Interfaces.C.int) with
   Import        => True,
   Convention    => C,
   External_Name => "foo";

procedure Test_Foo is
   type Double_Array is array (Positive range <>) of aliased Interfaces.C.double;
   A : Double_Array (1 .. 10) := (1.0, 2.0, 3.0, 4.0, 5.0,
                                  6.0, 7.0, 8.0, 9.0, 10.0);
begin
   C_Foo (A (A'First)'Access, A'Length);
end Test_Foo;

The function can be called however you want, it doesn't have to be C_Foo.

Be careful with C arrays, because in Ada they aren't pointers. Check the package Interfaces.C.Pointers_ to see how to better interface with C arrays.

New implementation...
< >
tkoenig