我的帮助程序函数返回一个空字符串



我正在为游戏编写一些代码,并尝试编写一个辅助函数来返回对象内的字符串:

const char* getGhostName(GhostAI* ghostAI)
{
if (ghostAI) {
GhostInfo* ghostInfo = getGhostInfo(ghostAI);
const auto ghostName = ghostInfo->fields.u0A6Du0A67u0A74u0A71u0A71u0A66u0A65u0A68u0A74u0A6Au0A6F.u0A65u0A66u0A6Eu0A67u0A69u0A74u0A69u0A65u0A74u0A6Fu0A67;
const char* name = il2cppi_to_string(ghostName).c_str();
return name;
}
return "UNKNOWN";
}

以下是il2cppi_to_string函数:

std::string il2cppi_to_string(Il2CppString* str) {
std::u16string u16(reinterpret_cast<const char16_t*>(str->chars));
return std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>{}.to_bytes(u16);
}
std::string il2cppi_to_string(app::String* str) {
return il2cppi_to_string(reinterpret_cast<Il2CppString*>(str));
}

当我调用getGhostName时,我最终得到一个空字符串。现在我确实收到了ReSharper的警告,上面写着:

支持指针的对象将在完整表达式结束时销毁。

调用il2cppi_to_string时,这出现在getGhostName内部的以下行中:

const char* name = il2cppi_to_string(ghostName).c_str();

我不完全确定这意味着什么或如何修改代码来修复它。我非常讨厌在C++中使用字符串。

il2cppi_to_string()返回一个临时std::string,它将在调用il2cppi_to_string()的表达式末尾被销毁。您正在获得指向该临时std::string数据的const char*指针,这是ReSharper警告您的。由于临时std::stringreturn之前被销毁,这意味着getGhostName()返回一个指向无效内存的悬空指针

要解决此问题,请将getGhostName()更改为返回std::string而不是const char*

std::string getGhostName(GhostAI* ghostAI)
{
if (ghostAI) {
GhostInfo* ghostInfo = getGhostInfo(ghostAI);
const auto ghostName = ghostInfo->fields.u0A6Du0A67u0A74u0A71u0A71u0A66u0A65u0A68u0A74u0A6Au0A6F.u0A65u0A66u0A6Eu0A67u0A69u0A74u0A69u0A65u0A74u0A6Fu0A67;
return il2cppi_to_string(ghostName);
}
return "UNKNOWN";
}

相关内容

最新更新