它是使用可变参数在C API设置键值对一个好主意? [英] Is it a good idea to use varargs in a C API to set key value pairs?

查看:95
本文介绍了它是使用可变参数在C API设置键值对一个好主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写在一个结构更新不同领域的大量的API。

I am writing an API that updates a LOT of different fields in a structure.

我可以通过更新功能可变参数有助于增加未来的字段:

I could help the addition of future fields by making the update function variadic:

update(FIELD_NAME1, 10, FIELD_NAME2, 20);

然后再添加 FIELD_NAME3 与出改变任何现有的电话:

then later add FIELD_NAME3 with out changing any existing calls:

update(FIELD_NAME1, 10, FIELD_NAME2, 20, FIELD_NAME3, 30);

的至理名言吗?

推荐答案

一般来说,没有。

可变参数抛出了很多类型安全的 - 你可以通过指针,花车等,而不是整数,它将编译没有问题。可变参数,如省略参数滥用,可以引入由于堆栈损坏,或阅读无效指针的奇怪崩溃。

Varargs throws out a lot of type-safety - you could pass pointers, floats, etc., instead of ints and it will compile without issue. Misuse of varargs, such as omitting arguments, can introduce odd crashes due to stack corruption, or reading invalid pointers.

例如,下面的调用将编译并导致崩溃或其他奇怪的行为:

For instance, the following call will compile and result in crashes or other odd behavior:

UpdateField(6, "Field1", 7, "Field2", "Foo");

最初的6多少个参数的期望。它将字符串指针富转换为int摆在Field2中,它会尝试读取和跨preT另外两个参数不能present,这很可能会从这里提领导致崩溃叠噪声。

The initial 6 is how many parameters to expect. It will convert the string pointer "Foo" to an int to put in Field2, and it will try to read and interpret two other parameters that aren't present, which will probably cause a crash here from dereferencing stack noise.

我相信用C可变参数的实现是一个错误(在今天的环境 - 它可能在1972年非常有意义)的实施是你在栈上传递了一堆数值,然后被叫方会走栈回升参数的基础上,一些初步的控制参数的相互pretation。这种类型的实现基本上尖叫为你做什么可能是一个非常难以诊断的方法是错误的。 C#的实现这一点,传递对象的数组,数组的方法的属性,只是必须理智,虽然没有直接可映射到C语言。

I believe the implementation of varargs in C is a mistake (given today's environment - it probably made perfect sense in 1972.) The implementation is you pass a bunch of values on the stack and then the callee will walk the stack picking up parameters, based on its interpretation of some initial control parameter. This type of implementation basically screams for you to make a mistake in what might be a very difficult to diagnose way. C#'s implementation of this, passing an array of objects with an attribute on the method, is just must saner, albeit not directly mappable into the C language.

这篇关于它是使用可变参数在C API设置键值对一个好主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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