调用C函数的参数过多 [英] Calling C functions with too many arguments

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

问题描述

我目前正在更改应用程序中一类函数的函数签名。这些功能存储在功能表中,因此我也希望更改此功能表。我刚刚意识到,在某些情况下,我们已经使用了新的函数签名。但是,因为所有内容在放入函数表时都被转换为正确的函数类型,所以不会引发警告。

I am currently changing the function signatures of a class of functions in an application. These functions are being stored in a function table, so I was expecting to change this function table as well. I have just realised that in certain instances, we already use the new function signature. But because everything is casted to the correct function type as it is put into the function table, no warnings are being raised.

调用该函数时,它将被传递多余的参数实际上不是函数声明的一部分,但它们位于参数列表的末尾。

When the function is called, it will be passed extra parameters that are not really part of the function declaration, but they are on the end of the parameter list.

我无法确定这是否可以保证函数参数在C中传递。我猜想做像sprintf这样的可变函数,必须是这样的情况,无论参数列表末尾是什么,早期的参数都可以正确解析?

I can't determine if this is guaranteed by the way function parameters are passed in C. I guess to do variadic functions like sprintf, it has to be the case that earlier arguments can be resolved correctly whatever is on the end of the parameter list?

它显然可以在多个平台上正常工作,但是出于好奇,我想知道它是如何工作的,为什么。

It evidently works just fine across multiple platforms but out of curiosity I'd like to know how and why it works.

推荐答案

您的函数肯定必须使用 cdecl 调用约定( http://en.wikipedia.org/wiki/X86_calling_conventions#cdecl )。这会将参数以从右到左的相反顺序推入堆栈,以确保最后一个参数可以轻松定位(位于堆栈顶部)并用于解释其余参数,例如 printf 格式字符串。清理堆栈也是调用者的责任,它比函数本身的紧凑程度小(如 pascal / stdcall 约定),但可以确保可以使用可变参数列表,并表示可以忽略尾随参数。

Your functions must certainly be using the cdecl calling convention (http://en.wikipedia.org/wiki/X86_calling_conventions#cdecl). This pushes arguments on the stack in reverse order, from right to left, ensuring that the last argument can be easily located (top of the stack) and used to interpret the remainder, such as a printf format string. It is also the responsibility of the caller to clean up the stack, which is a bit less compact than the function itself doing so (as in pascal/stdcall convention), but ensures that variable argument lists can be used, and implies that trailing arguments can be ignored.

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

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