3 回答

TA貢獻1853條經驗 獲得超18個贊
我會說這是現代的C ++方式。
#include <cstdint>
void *p;
auto i = reinterpret_cast<std::uintptr_t>(p);
編輯:
正確的整數類型
因此將指針存儲為整數的正確方法是使用uintptr_tor intptr_t類型。(另請參見c99的 cppreference 整數類型)。
這些類型在<stdint.h>C99 中定義,在stdC ++ 11中的命名空間中定義<cstdint>(請參閱C ++的整數類型)。
C ++ 11(及更高版本)版本
#include <cstdint>
std::uintptr_t i;
C ++ 03版本
extern "C" {
#include <stdint.h>
}
uintptr_t i;
C99版本
#include <stdint.h>
uintptr_t i;
正確的鑄造工人
在C語言中,只有一個強制轉換,而在C ++中使用C強制轉換卻不受歡迎(因此請不要在C ++中使用它)。在C ++中,有不同的強制轉換。reinterpret_cast是此轉換的正確轉換(另請參見此處)。
C ++ 11版本
auto i = reinterpret_cast<std::uintptr_t>(p);
C ++ 03版本
uintptr_t i = reinterpret_cast<uintptr_t>(p);
C版
uintptr_t i = (uintptr_t)p; // C Version

TA貢獻1816條經驗 獲得超4個贊
有幾個答案指出uintptr_t并#include <stdint.h>稱為“解決方案”。我建議,這是答案的一部分,而不是全部答案。您還需要查看消息ID為FOO的函數的調用位置。
考慮以下代碼和編譯:
$ cat kk.c
#include <stdio.h>
static void function(int n, void *p)
{
unsigned long z = *(unsigned long *)p;
printf("%d - %lu\n", n, z);
}
int main(void)
{
function(1, 2);
return(0);
}
$ rmk kk
gcc -m64 -g -O -std=c99 -pedantic -Wall -Wshadow -Wpointer-arith \
-Wcast-qual -Wstrict-prototypes -Wmissing-prototypes \
-D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE kk.c -o kk
kk.c: In function 'main':
kk.c:10: warning: passing argument 2 of 'func' makes pointer from integer without a cast
$
您會發現在調用位置(中的main())存在問題-將整數轉換為沒有強制轉換的指針。您將需要分析function()其所有用法,以了解如何將值傳遞給它。function()如果調用被編寫,我內部的代碼將起作用:
unsigned long i = 0x2341;
function(1, &i);
由于您的編寫方式可能有所不同,因此您需要檢查調用該函數的要點,以確保使用所示值有意義。別忘了,您可能會發現一個潛在的錯誤。
另外,如果您要格式化void *參數的值(轉換后的格式),請仔細查看<inttypes.h>標題(而不是stdint.h— inttypes.h提供的服務stdint.h,這是不尋常的,但是C99標準指出,標題<inttypes.h>包含標題<stdint.h>和通過托管實現提供的其他功能對其進行擴展),并在格式字符串中使用PRIxxx宏。
另外,我的評論嚴格適用于C而不是C ++,但是您的代碼位于C ++的子集中,該子集可在C和C ++之間移植。我的評論適用的機會是公平的。
- 3 回答
- 0 關注
- 1602 瀏覽
添加回答
舉報