从 Ada 调用 scanf
如何从 Ada 调用 scanf ?也就是说,大概有一个适当的 pragma import 声明,但是声明会是什么样子呢?
(我感兴趣的是如何从 Ada 调用更不规则的 C 函数,而不是如何解析字符串本身,所以我不是在寻找纯粹的 Ada 解决方案。我的设置是 Gnat、Ubuntu Linux、x64(如果它是)有所作为。)
How do you call scanf from Ada? That is, presumably with an appropriate pragma import declaration, but what would the declaration look like?
(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.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
本文要点出那个
scanf()
也是如此,它在 Ada 2012 中具有额外的好处,可以让您在out
和access
参数规格之间进行选择(在早期版本中,您必须使用access
因为函数不允许具有out
参数)。此外,我不认为 C 编译器必须对可变参数函数使用与普通函数相同的参数传递机制 (参考暗示了这一点,我记得但现在找不到关于这些线路的最近对话)。
也就是说,这里有一个在带有 GCC 4.6.0 的 Mac OS X 上运行良好的示例:(
不确定格式参数中的
\n
!)This paper points out that
The same would be true of
scanf()
, which with Ada 2012 has the added bonus of letting you choose betweenout
andaccess
parameter specs (in earlier revisions, you had to useaccess
because functions weren’t allowed to haveout
parameters).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).
That said, here’s an example which appears to work fine on Mac OS X with GCC 4.6.0:
(not sure about the
\n
in the format parameter!)一种解决方法是在 C 中声明多个非可变参数包装函数,并将它们导入到 Ada 中。
例如:
然后使用
pragma Import
在Ada中声明重载的scan()函数。这样,您就不会尝试从 Ada 调用可变参数函数;而是尝试从 Ada 调用可变参数函数。所有固定到可变的转换都发生在 C 端。只要所有包装器都正确编写,您就可以获得比直接调用
scanf()
更多的类型检查。您只需要为您想要传递的每组参数类型提供一个不同的包装器。
如果您只有几个调用,这可能没问题,但它的扩展性不好。
One workaround would be to declare multiple non-variadic wrapper functions in C, and import them in Ada.
For example:
and then declare overloaded scan() function in Ada with
pragma Import
.This way, you're not attempting to call variadic functions from Ada; all the fixed-to-variadic conversion happens on the C side. And as long as all the wrappers are written correctly, you get more type checking than you would with a direct call to
scanf()
.You just need a distinct wrapper for each set of parmaeter types you want to pass.
This is probably ok if you only have a few calls, but it doesn't scale well.