Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic function in Ada (C - Ada binding)?

I am working on a project which uses C - Ada language binding. A function in C will call a function in Ada side. I want to make a variadic function in Ada which can receive a variable number of arguments sent from the C function. I also wanted to send different types of args at the same time like int, char, enums, etc at the same time. Is it possible to have this type of mechanism?

like image 419
Akay Avatar asked Mar 05 '16 19:03

Akay


People also ask

What is the purpose of Variadic functions?

Variadic functions are functions that can take a variable number of arguments. In C programming, a variadic function adds flexibility to the program. It takes one fixed argument and then any number of arguments can be passed.

What is the meaning of variadic?

variadic (not comparable) (computing, mathematics, linguistics) Taking a variable number of arguments; especially, taking arbitrarily many arguments.

What is in out in Ada?

in out is a parameter with an initial value provided by the caller, which can be modified by the subprogram and returned to the caller (more or less the equivalent of a non-constant reference in C++). Ada also provides access parameters, in effect an explicit pass-by-reference indicator.


3 Answers

The forthcoming Ada standard Ada 202x is planning to provide support for calling C variadic functions.

You would then be able to write;

package C renames Interfaces.C;

procedure Printf (Format : in C.char_array)
  with Import => True, Convention => C_Variadic_1, External_Name => "printf";
like image 60
B. Moore Avatar answered Sep 20 '22 02:09

B. Moore


You cannot create a variadic function in Ada. You can simulate a variadic function is a couple of ways.

  1. Ada allows you to specify default values for functions and procedures. One need not always specify the values of the default parameters if you want to use the default values.
  2. You can define one or more of the parameters as a variant record.
like image 29
Jim Rogers Avatar answered Sep 22 '22 02:09

Jim Rogers


It is not possible to call any C variadic function from Ada in a portable way!

One of the reason - some ABIs use special ways/registers to pass float values. This mean C compiler will use this registers, due to it's unknown in advance whether argument is float or not. Ada compiler will not use this registers (since you can't put float parameter in Ada wrapper function declaration). As result you will get crash, stack corruption or any other undefined behavior.

Particularly AMD64 ABI specifies:

%rax - with variable arguments passes information about the number of vector registers used

%xmm0–%xmm1 - used to pass and return floating point arguments

The only portable solution is using C wrapper with fixed number of parameters, then bind it as usual.

like image 27
Maxim Reznik Avatar answered Sep 23 '22 02:09

Maxim Reznik