简体   繁体   English

从 function 返回 const char* 的问题

[英]Problems returning const char* from function

First, thanks for taking some time helping me.首先,感谢您花时间帮助我。

I am working on Arduino, and the thing is that I need to return a const char* on a function.我正在研究 Arduino,问题是我需要在 function 上返回一个 const char*。

What I need to do is to create a String and send the response back.我需要做的是创建一个字符串并将响应发回。 Things like this are not working:像这样的事情不起作用:

...
String myVar= "Return Message";
return RPC_Response(myVar);
}

This didn't work, the String seems to be erased.这不起作用,字符串似乎被删除了。 Since I just get a blank response:因为我只是得到一个空白的回复:

...
    const char* ch = new char;
    String myVar= "Return Message";
    ch = myVar.c_str();
    
    return RPC_Response(ch); 
}

But it only works If I do something like this: (But I need to create a String dynamically...)但它只有在我做这样的事情时才有效:(但我需要动态创建一个字符串......)

. .

char *msg1 = "Return Message";
return RPC_Response(chmsg1); 
}

Or something like this:或者是这样的:

. .

return RPC_Response("Return Message"); 
}

I have tried almost everything but nothing works...我几乎尝试了所有方法,但没有任何效果......

Please...?请...? Any idea of what Can I do???知道我能做什么吗???

First of all, you could simplify your code to the following:首先,您可以将代码简化为以下内容:

    std::string myVar= "Return Message";
    return RPC_Response(myVar.c_str()); 

This will not work though, because the result of c_str() gets invalidated when a string gets modified, including the string being destroyed.但这不起作用,因为当字符串被修改时c_str()的结果会失效,包括被销毁的字符串。

The reason using a string literal works is because string literals are stored globally.使用字符串文字的原因是因为字符串文字是全局存储的。 (It's actually implementation defined, but typically it is done so) (它实际上是定义的实现,但通常是这样做的)

// storing it in a char* variable first is equivalent
return RPC_Response("Return Message");

Assuming RPC_Response only accepts C-strings, you would have do to this:假设RPC_Response只接受 C 字符串,你必须这样做:

#include <string.h>
...

std::string myVar = "Return Message";
char* str = strdup(myVar.c_str());
return RPC_Response(str);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM