[英]How can I set a uintptr_t value to address of non uintptr_t function?
void __fastcall func1(void* ptr, int edxReg)
{
int a = 5;
}
我想獲取此函數的地址並將其設置為uintptr_t
變量:
std::uintptr_t addr = &func1;
但是,我不能這樣做,因為它不能從void(__fastcall)(void*, int)
轉換為uintptr_t
。
我嘗試使用 C++ 風格的鑄造,但沒有運氣,它只是給了我一個隨機值。
我能做些什么呢? 名為func1
的 function 必須保持原樣,它必須是帶有 2 個參數的void __fastcall
,因此無法更改。
C++ 風格的轉換在這里是合適的,特別是reinterpret_cast
:
使用 reinterpret_cast 只能完成以下轉換,除非此類轉換會拋棄常量或易變性。
...
指針可以轉換為任何大到足以容納其類型的所有值的整數類型(例如到 std::uintptr_t)
任何整數或枚舉類型的值都可以轉換為指針類型。 轉換為足夠大小的 integer 並返回相同指針類型的指針保證具有其原始值,否則無法安全地取消引用生成的指針(不保證相反方向的往返轉換;相同的指針可能have multiple integer representations) The null pointer constant NULL or integer zero is not guaranteed to yield the null pointer value of the target type; 為此應使用 static_cast 或隱式轉換。
...
因此,例如:
void __fastcall func1(void* ptr, int edxReg)
{
int a = 5;
}
std::uintptr_t addr = reinterpret_cast<std::uintptr_t>(&func1);
然后在需要時,您可以將uintptr_t
回適當簽名的 function 指針,以便調用指向的 function,例如:
typedef void __fastcall (*funcType)(void*, int);
// or: using funcType = void __fastcall (*)(void*, int);
funcType func = reinterpret_cast<funcType>(addr);
func(somePtr, someEdxRegVal);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.