Is there a way to get a float from the parameters of the varargs function?

If the function was defined with a prototype that explicitly specified parameter types, for example.

void somefunc(int arg1, float arg2);

but implemented as

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

Can va_arg be used to get a float? This usually prevents this, because varargs functions have implicit type promotions such as float to double, so trying to get a nonprotected type is not supported, although the function is called using a nonprotected type for a more specific function prototype.

The reason for this is to extract arguments of different types at run time, as part of the obj-c interpreter, where one function will be reused for all different types of methods.

This would be best since the architecture would not be independent (so if not the same code works on the simulator and on the device), although if there is no way to do this, specific corrections will be made for the specific device.

EDIT: forgot to mention specifically: the function knows the types and number of arguments (it looks at the code that needs to be interpreted using a map search using the SEL _cmd parameter)

+3
source share
4 answers

You can do the following:

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 as follows:

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

In your function, you then execute

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
}

This avoids the problem of unnecessary promotions and does not require assembly language.

, . varargs, varargs, period. bbum, ABI .

+3

. -, varargs, , , ABI varargs ABI -varargs; -, .

- , . "em" .

, , ABI, , .

, - . objc_msgSend(), , , Objective-C (: , - ).

+6

​​ , , -, . . . C. , .

/ - , . .

+2

You can always cut varargs and instead encode all your parameters into a string. The interface of your function remains constant, and you have complete freedom to interpret the data, however you need to. However, this is not a very pleasant solution, since you are essentially using a script parser.

0
source

Source: https://habr.com/ru/post/1746419/


All Articles