The*_*One 1 c++ string pointers reverse-engineering
我正在为游戏编写一些代码,并尝试编写一个辅助函数来返回对象内的字符串:
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";
}
Run Code Online (Sandbox Code Playgroud)
这是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));
}
Run Code Online (Sandbox Code Playgroud)
当我调用 时getGhostName,我最终得到一个空字符串。现在我确实收到了来自 ReSharper 的警告,其中写着:
支持指针的对象将在完整表达式的末尾被销毁。
getGhostName调用时,这会出现在以下行中il2cppi_to_string:
const char* name = il2cppi_to_string(ghostName).c_str();
Run Code Online (Sandbox Code Playgroud)
我不完全确定这意味着什么或如何修改代码来修复它。我绝对讨厌在 C++ 中使用字符串。
il2cppi_to_string()返回一个临时的 std::string,它将在调用 的表达式末尾被销毁il2cppi_to_string()。您正在获取指向该临时const char*数据的指针,这就是 ReSharper 警告您的内容。由于临时对象在 之前被销毁,这意味着返回一个指向无效内存的悬空指针。 std::string std::stringreturngetGhostName()
要解决此问题,请更改getGhostName()为返回 astd::string而不是 a 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";
}
Run Code Online (Sandbox Code Playgroud)