您正在返回函数本地的地址。它仅在该函数的持续时间内存在。
char* GetWindowTitle(HWND hwnd) {
char winTitle[56]; <====== this is destroyed when the function ends
GetWindowTextA(hwnd, winTitle, sizeof(winTitle));
printf("Title: %s\n", winTitle);
return winTitle;
}
试试这个:
#include <string>
std::string GetWindowTitle(HWND hwnd) {
char winTitle[56];
GetWindowTextA(hwnd, winTitle, sizeof(winTitle));
printf("Title: %s\n", winTitle);
return std::string(winTitle);
}
这将在堆上分配一个std::string。一旦你不再在调用代码中引用它,它就会被删除。
要使用printf() 显示此字符串,请执行以下操作:
printf("Title: %s\n", GetWindowTitle(hwnd).c_str());
不过,您应该改掉使用 C 风格 I/O(printf() 等)的习惯。要使用 C++ 风格的 I/O 显示此字符串,请执行以下操作:
#include <iostream>
std::cout << "Title: " << GetWindowTitle(hwnd) << std::endl;
如果你打算写大量的C++代码,学会使用:
-
std::string(C# 中的string)
-
std::shared_ptr 和 std::unique_ptr(C# 中的类对象引用)
-
std::vector(C# 中的List)
-
std::map(C# 中的Dictionary)