我在初始化结构指针时遇到了一些问题。
struct Hook{
DWORD64 Address;
vector<BYTE> OriginalBytes;
vector<BYTE> HookBytes;
SIZE_T length;
bool Initialized;
};
Hook *hFuncHook;
void InitializeHookInfo(Hook* hook, DWORD64 address, SIZE_T size){
hook = new Hook;
hook->Address = address;
hook->OriginalBytes = GetAOB(address, size);
hook->HookBytes.reserve(size);
hook->length = size;
hook->Initialized = false;
}
void EndHookInfoInit(Hook* hook, DWORD64 address, SIZE_T size){
printf("Hook size: %i\n", sizeof(hook)); //returns 8
hook->HookBytes = GetAOB(address, size);//Crash right there
hook->Initialized = true;
}
void InitMyHooks(){
InitializeHookInfo(hFuncHook, mBase + 0xA100FC, 6);
HookFunction(...);
EndHookInfoInit(hFuncHook, mBase + 0xA100FC, 6);
}
我无法弄清楚为什么会崩溃。 InitializeHookInfo部分不会导致任何问题,但EndHookInfoInit只会崩溃。
删除hook->HookBytes = GetAOB(...);
也会导致崩溃
答案 0 :(得分:0)
指针(T*
)并不比一个变量更复杂,该变量的值将被视为T实例的内存中的地址,除非它包含nullptr
的值。
将变量传递给C ++函数的默认行为是按值传递。
int f(int i) { // i is local copy of source parameter
i = 2; // only modifies local copy
}
传递指针
时没有什么不同int f(T* p) {
p = new T;
}
您的代码按值获取指针:
void InitializeHookInfo(Hook* hook, DWORD64 address, SIZE_T size);
所以这行代码:
InitializeHookInfo(hFuncHook, mBase + 0xA100FC, 6);
将hFuncHook的值复制到函数的第一个参数槽中,InitializeHookInfo
void InitializeHookInfo(Hook* hook, DWORD64 address, SIZE_T size) {
hook = new Hook;
这会分配一个新的Hook并将地址分配给一个本地变量。
你应该考虑:
一个。从函数中返回指针
Hook* InitializeHookInfo(DWORD64 address, SIZE_T size) {
Hook* hook = new Hook;
// ...
return hook;
}
湾按地址指针
void InitializeHookInfo(Hook** hook, DWORD64 address, SIZE_T size) {
*hook = new Hook;
℃。通过引用获取指针(稍微讨厌,因为它不透明)
void InitializeHookInfo(Hook*& hook, DWORD64 address, SIZE_T size) {
hook = new Hook; // affects source parameter
或者您可能更愿意考虑使用成员函数
struct Hook{
DWORD64 Address { 0 };
vector<BYTE> OriginalBytes;
vector<BYTE> HookBytes;
SIZE_T length { 0 };
bool Initialized { false };
Hook() {}
Hook(DWORD64 address, SIZE_T size)
: Address { address }
, OriginalBytes { GetAOB(address, size) }
, length(size)
{
HookBytes.reserve(size);
}
void EndInit(DWORD64 address, SIZE_T size)
{
std::cout << "Hook size: " << sizeof(*this) << "\n";
HookBytes = GetAOB(address, size); // didn't we already do this?
Initialized = true;
}
};
std::unique_ptr<Hook> hFuncHook;
void InitMyHooks()
{
hFuncHook = std::make_unique<Hook>(mBase + 0xA100FC, 6);
HookFunction(hFuncHook.get());
hFuncHook->EndInit(mBase + 0xA100FC, 6);
}
最后,
printf("Hook size: %i\n", sizeof(hook)); //returns 8
这是因为hook
是指针,您正在打印
printf("Hook size: %i\n", sizeof(Hook*)); //returns 8
你可能想要
printf("Hook size: %i\n", sizeof(*hook)); //returns 8