有什么办法来检索一个可变参数函数的参数的浮动? [英] Is there any way to retrieve a float from a varargs function's parameters?

查看:89
本文介绍了有什么办法来检索一个可变参数函数的参数的浮动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果该函数与原型,其中明确规定的参数类型,定义如:

If the function was defined with a prototype which explicitly stated the types of the parameters, eg.

void somefunc(int arg1, float arg2);

,但被实现为

void somefunc(int arg1, ...) { ... }

是有可能使用的va_arg检索浮?它通常美元,这样做是因为pvented p $可变参数函数具有隐式类型的促销活动,像浮翻一番,所以试图检索未促进的类型是不支持的,即使函数被调用的未促进的类型做了更具体的函数原型

is it possible to use va_arg to retrieve a float? It's normally prevented from doing this because varargs functions have implicit type promotions, like float to double, so trying to retrieve an unpromoted type is unsupported, even though the function is being called with the unpromoted type do to the more specific function prototype.

这样做的理由是检索不同类型的在运行时的参数,如一个对象 - 间preTER,其中一个函数将所有不同类型的方法被重复使用的部分

The reason for this is to retrieve arguments of different types at runtime, as part of an obj-c interpreter, where one function will be reused for all different types of methods.

这将是最好的架构独立的(因此,如果没有其他相同code ++工程,设备模拟器和),但如果没有办法做到这一点,然后设备特定补丁将被接受。

This would be best as architecture independent (so that if nothing else the same code works on simulator and on device), although if there is no way to do this then device specific fixes will be accepted.

编辑:
忘了明确提到:函数知道的类型和参数计数(它看起来了code能与用SEL _cmd参数地图查找PTED间$ P $)

forgot to mention specifically: the function knows the types and count of the arguments (it looks up the code to be interpreted with a map lookup with the SEL _cmd parameter)

推荐答案

您可以做到以下几点:

static inline uint32_t floatparam (float f) {
  union { uint32_t u; float f; } u;
  u.f = f;
  return u.u;
}

然后始终调用你的函数,像这样:

then always call your function like so:

fn(5, floatparam(0.5f), floatparam(1.1f), ...);

在你的函数,那么你会做

In your function, you'd then do

va_list val;

va_start (val, arg1);
while (<more arguments>) {
  union { float f; uint32_t u; } u;
  u.u = va_arg (val, uint32_t);
  // float is now in u.f
}

这避免了不必要的类型优惠的问题,并且不需要汇编语言

That avoids the problem of needless type promotions, and doesn't require assembly language.

当然,你不应该错误地声明你的函数。如果它是一个可变参数的函数,这是一个可变参数的函数,期限。作为bbum称,ABI是不同的。

Of course, you shouldn't mis-declare your function. If it's a varargs function, it's a varargs function, period. As bbum says, the ABI is different.

这篇关于有什么办法来检索一个可变参数函数的参数的浮动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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