从Ada调用scanf [英] Calling scanf from Ada

查看:89
本文介绍了从Ada调用scanf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何从Ada呼叫scanf?也就是说,大概带有一个适当的pragma导入声明,但是该声明会是什么样子?

How do you call scanf from Ada? That is, presumably with an appropriate pragma import declaration, but what would the declaration look like?

(我对如何调用更不规则的C函数感兴趣)

(I'm interested in how to call C functions of the more unruly variety from Ada, not how to parse strings per se, so I'm not looking for a pure Ada solution. My setup is Gnat, Ubuntu Linux, x64 if it makes a difference.)

推荐答案

本文指出


Ada无法声明采用不同数字的函数不同类型的参数。可以声明一组 printf函数,这些函数采用一个字符串,一个字符串和一个整数,一个字符串和一个浮点数,一个字符串和两个整数,依此类推,然后将每个声明为Import(C) 2。但这需要大量的声明,每种声明针对应用程序中的每种不同用途,因此它实际上是不实际的。

Ada has no way of declaring a function that takes different numbers of parameters of different types. One could declare a set of "printf" functions which take a string, a string and an integer, a string and a floating point number, a string and 2 integers, and so on, and then declare each one to be Import (C)2. But this requires lots of declarations, one for each different kind of use in the application program, so it really isn’t practical.

scanf()也是如此,在Ada 2012中,它具有让您在 out 之间进行选择的额外好处。和 access 参数规范(在较早的版本中,必须使用 access ,因为不允许函数具有 out 参数)。

The same would be true of scanf(), which with Ada 2012 has the added bonus of letting you choose between out and access parameter specs (in earlier revisions, you had to use access because functions weren’t allowed to have out parameters).

此外,我不认为C编译器必须使用相同的参数可变函数的传递机制,就像普通函数一样(参考暗示了这一点,我记得但现在无法在这些行上找到最近的对话。)

In addition, I don’t believe it’s required that the C compiler has to use the same parameter passing mechanisms for variadic functions as it does for ordinary ones (the reference hints at this, and I recall but can’t now find a recent conversation on these lines).

这是一个在GCC 4.6.0的Mac OS X上似乎可以正常工作的示例:

That said, here’s an example which appears to work fine on Mac OS X with GCC 4.6.0:

with Ada.Text_IO; use Ada.Text_IO;
with Interfaces.C; use Interfaces.C;
procedure Variadic is
   function Scanf (Fmt : char_array; Result : access int) return int;
   pragma Import (C, Scanf, "scanf");
   Status : int;
   Result : aliased int;
begin
   Status := Scanf (To_C ("%d\n"), Result'Access);
   Put_Line ("status: " & int'Image (Status));
   if Status = 1 then
      Put_Line ("result: " & int'Image (Result));
   end if;
end Variadic;

(不确定 \n 在format参数中!)

(not sure about the \n in the format parameter!)

这篇关于从Ada调用scanf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆