[英]Handling of const char* on ESP32
我正在對 ESP32 進行一些 Spotify API 調用。 我對 C++ 還很陌生,雖然我似乎讓它按照我想要的方式工作,但我想知道這是否是正確的方法/最佳實踐,或者我是否只是幸運。 不管我讀了多少,關於字符和指針的整個事情對我來說仍然很困惑。
我正在調用 Spotify API,獲得 json 響應並使用 ArduinoJson 庫對其進行解析。 該庫將所有鍵和值作為const char*
返回。我用來在屏幕上顯示它的庫也采用const char*
。 我在將它轉換為字符串之前讓它工作,使用 getTitle() function 返回字符串並將其轉換回屏幕上顯示。 在我讀到字符串效率低下且最好避免之后,我嘗試減少轉換步驟。
void getTitle()
{
// I cut out the HTTP request and stuff
DynamicJsonDocument doc(1024);
DeserializationError error = deserializeJson(doc, http.getStream(), );
JsonObject item = doc["item"];
title = item["name"]; //This is a const char*
}
const char* title = nullptr;
void loop(void) {
getTitle();
u8g2.clearBuffer();
u8g2.setDrawColor(1);
u8g2.setFont(u8g2_font_6x12_tf);
u8g2.drawStr(1, 10, title);
u8g2.sendBuffer();
}
這樣做可以嗎?
當看到這樣的事情時,你應該立即產生懷疑。
這是因為在getTitle
中,您正在向本地object ( item
) 請求指針 - 但您稍后使用該指針,此時item
object 不再存在。
這意味着一旦你需要它,你的指針可能毫無意義——它可能不再引用你的數據,而是一些任意的其他字節(甚至導致崩潰)。
此問題與您使用的確切庫無關,您通常可以通過在庫文檔中搜索“生命周期”或“對象所有權”來找到相關的、更具體的信息。
確保該item
(以及DynamicJsonDocument
,因為文檔告訴您)在您使用數據時仍然存在。 例如:像這樣:
void setTitle(const char *title)
{
u8g2.clearBuffer();
u8g2.setDrawColor(1);
u8g2.setFont(u8g2_font_6x12_tf);
u8g2.drawStr(1, 10, title);
u8g2.sendBuffer();
}
void updateTitle()
{
DynamicJsonDocument doc(1024);
DeserializationError error = deserializeJson(doc, http.getStream(), );
JsonObject item = doc["item"];
setTitle(item["name"]);
}
另請參閱: https://arduinojson.org/v6/how-to/reuse-a-json-document/#the-best-way-to-use-arduinojson
您可以在需要解析數據時保持 JSON 文檔“活動”:
/* "static" visibility, so that other c/cpp files ("translation units") can't
* mess mess with our JSON doc directly
*/
static DynamicJsonDocument doc(1024);
static const char *title;
void parseJson()
{
[...]
// super important to avoid leaking memory!!
doc.clear();
DeserializationError error = deserializeJson(doc, http.getStream(), );
// TODO: robustness/error handling (e.g. inbound JSON is missing "item")
title = doc["item"]["name"];
}
// may be nullptr when called before valid JSON was parsed
const char* getTitle()
{
return title;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.