vararg 函数如何找出机器代码中的参数数量? [英] How do vararg functions find out the number of arguments in machine code?

查看:23
本文介绍了vararg 函数如何找出机器代码中的参数数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

printf 这样的可变参数函数如何找出它们得到的参数数量?

How can variadic functions like printf find out the number of arguments they got?

参数的数量显然不是作为(隐藏的)参数传递的(参见 在此处的 asm 示例中调用 printf).

The amount of arguments obviously isn't passed as a (hidden) parameter (see a call to printf in asm example here).

有什么诀窍?

推荐答案

诀窍在于你以其他方式告诉他们.对于 printf,您必须提供一个格式字符串,其中甚至包含类型信息(尽管这可能不正确).提供此信息的方式主要是用户合同,而且通常容易出错.

The trick is that you tell them somehow else. For printf you have to supply a format string which even contains type information (which might be incorrect though). The way to supply this information is mainly user-contract and often error-prone.

至于调用约定:通常是从左到右将参数压入栈中,最后是回跳地址.调用例程清除堆栈.所以被调用的例程不需要知道参数的个数.

As for calling conventions: Usually the arguments are pushed onto the stack from left to right and then the backjump address at last. The calling routine clears the stack. So there is no technical need for the called routine to know the number of parameters.

在 C++0x 中有一种安全的方式(甚至类型安全!)来调用可变参数函数!

In C++0x there is a safe way (even typesafe!) to call variadic functions!

这篇关于vararg 函数如何找出机器代码中的参数数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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