Logo

Programming-Idioms

History of Idiom 190 > diff from v10 to v11

Edit summary for version 11 by ~jv~:
New Ada implementation by user [~jv~]

Version 10

2022-02-26, 20:59:04

Version 11

2023-10-14, 18:30:05

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.

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.

Variables
a,n
Variables
a,n
Extra Keywords
C interoperability
Extra Keywords
C interoperability
Imports
Interfaces.C
Code
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;
Comments bubble
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.