Arduino 上的可变参数函数
我正在 Arduino 022 中为 Arduino Mini Pro 进行编程。我有以下函数:
String join(const String str, ...) {
Serial.println("join");
va_list args;
va_start(args, str);
Serial.println("result init");
String result = "";
for (String strArg = str; strArg != NULL; strArg = va_arg(args, String)) {
Serial.println(result);
result += strArg + ARG_DELIMITER;
}
result = result.substring(0, result.length() - 1);
Serial.println("join end");
return result;
}
当我调用此函数时,程序暂停,并且引脚 13 中的内置 LED 亮起。 “join”永远不会打印到串行监视器。 Arduino 上不允许使用可变参数函数吗?
I am programming in Arduino 022 for the Arduino Mini Pro. I have the following function:
String join(const String str, ...) {
Serial.println("join");
va_list args;
va_start(args, str);
Serial.println("result init");
String result = "";
for (String strArg = str; strArg != NULL; strArg = va_arg(args, String)) {
Serial.println(result);
result += strArg + ARG_DELIMITER;
}
result = result.substring(0, result.length() - 1);
Serial.println("join end");
return result;
}
When I call this function, the program halts, and the built in LED in pin 13 turns on. "join" is never printed to the serial monitor. Are variadic functions not permitted on Arduino?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法将大多数类类型传递给可变参数函数 - 只能传递 POD 类型(标准中的 5.2.2 第 7 段);如果你这样做,行为是未定义的 - 这可能会导致你遇到的问题。我很确定 Arduino String 类 不是 POD,所以这不会工作。
您可能最好使用 char 数组(至少在某些地方),例如,
如果这不会在调用站点造成太多丑陋,或者可能只是提供 1 到 N 个字符串的重载。
另外 - String 对象可以等于 NULL 吗?您对
strArg != NULL
的测试看起来很可疑。You can't pass most class types to a variadic function - only POD types (5.2.2 para 7 in the standard); if you do the behaviour is undefined - which could cause the problems you're getting. I'm pretty sure the Arduino String class is not a POD, so this isn't going to work.
You might be better off using char arrays (at least in some places), eg
if this doesn't cause too much ugliness at the call site, or perhaps just provide overloads for 1 to N Strings.
Also - can a String object ever be equal to NULL? Your test for
strArg != NULL
looks dubious.当您调用代码时,它是否看起来像:
或:
您必须自己提供 NULL 终止符 - 编译器不会这样做。
编辑:这假设 String 是 char * 的 typedef (因为您将它与 NULL 进行比较),但如果是的话,您的代码还有很多其他错误。请澄清 String 的类型是什么。
When you call the code, does it look like:
or:
You have to provide the NULL terminator yourself - the compiler won't do it.
Edit: This assumes that String is a typedef for char * (because you compare it with NULL), but if it is there is much else wrong with your code. Please clarify what the type of String is.