va_list 的重用 [英] Reuse of va_list
问题描述
我需要对 va_list
执行两次(或多次)传递.我有一个一定大小的缓冲区,我想用 sprintf 将格式化的字符串写入其中.如果格式化的字符串不适合分配的空间,我想将分配的空间加倍并重复直到适合.
I need to do two (or more) passes over a va_list
. I have a buffer of some size, and I want to write a formatted string with sprintf into it. If the formatted string doesn't fit in the allocated space I want to double the allocated space and repeat until it fits.
(作为旁注,我希望能够首先计算格式化字符串的长度并分配足够的空间,但我发现可以做到这一点的唯一函数是 _snprintf,它在 VS2005 中已弃用...)
(As a side-note, i would like be able to calculate the length of the formatted string first and allocate enough space, but the only function that I found that can do that is _snprintf, and it is deprecated in VS2005 ...)
现在,到目前为止没有问题:我使用 vsnprintf
并在每次调用之前调用 va_start
.
Now, so far there are no problems: i use vsnprintf
and call va_start
before each invokation.
但我还创建了一个函数,它以 va_list
作为参数,而不是...".那我就不能再使用 va_start
了!我已经阅读了 va_copy
,但它在 VS2005 中不受支持.
But I've also created a function that takes a va_list
as a parameter, instead of "...". Then I cannot use va_start
again! I've read about va_copy
, but it is not supported in VS2005.
那么,你会怎么做?
推荐答案
我看到没有可移植的方式(我认为 va_copy 已在 C99 中引入,因为在 c89 中没有可移植的方式来实现其结果).va_list 可以是声明为
I see of no portable way (and I think that va_copy has been introduced in C99 because there was no portable way to achieve its result in c89). A va_list can be a reference type mock up declared as
typedef struct __va_list va_list[1];
(有关该技巧的另一个用户,请参阅 gmp),这解释了围绕它们的许多语言限制.顺便说一句,如果可移植性很重要,请不要忘记 va_end.
(see gmp for another user of that trick) and that explains a lot of the language constraints around them. BTW, don't forget the va_end if portability is important.
如果可移植性不重要,我会检查 stdard.h,看看我是否可以在考虑真实声明的情况下破解某些内容.
If portability is not important, I'd check stdard.h and see if I can hack something considering the true declaration.
这篇关于va_list 的重用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!