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

查看:17
本文介绍了在 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 抛出了很多类型安全问题——你可以传递指针、浮点数等,而不是整数,它会毫无问题地编译.误用可变参数(例如省略参数)可能会由于堆栈损坏或读取无效指针而导致奇怪的崩溃.

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 是期望的参数数量.它将字符串指针Foo"转换为 int 以放入 Field2,并尝试读取和解释另外两个不存在的参数,这可能会导致此处因取消引用堆栈噪声而导致崩溃.

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 中实现 varargs 是一个错误(考虑到今天的环境 - 它在 1972 年可能是完美的.)实现是你在堆栈上传递一堆值,然后被调用者将遍历堆栈参数,基于它对一些初始控制参数的解释.这种类型的实现基本上是在警告您以一种可能非常难以诊断的方式犯错误.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天全站免登陆