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?
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.
variadic (not comparable) (computing, mathematics, linguistics) Taking a variable number of arguments; especially, taking arbitrarily many arguments.
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.
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";
You cannot create a variadic function in Ada. You can simulate a variadic function is a couple of ways.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With