[英]Cast pointer address to int
Beginner question: How can I take the adress of a pointer and save it as an int?初学者问题:如何获取指针的地址并将其保存为 int? Example:
例子:
int *ptr = xyz;
int i = static_cast<int>(ptr);
So if ptr points to the memory adress 123, i should be 123. My compiler says it's an error: invalid static_cast from type 'int*' to type 'int'
.所以如果 ptr 指向内存地址 123,我应该是 123。我的编译器说这是一个
error: invalid static_cast from type 'int*' to type 'int'
。
Guess I am missing something but I don't know what.猜猜我错过了什么,但我不知道是什么。
You can use reinterpret_cast
.您可以使用
reinterpret_cast
。 An int
is not guaranteed to be able to losslessly store a pointer though, so you should use the std::intptr_t
type instead.但是,不能保证
int
能够无损地存储指针,因此您应该改用std::intptr_t
类型。
you can use the following function to get any pointer as unsigned long.您可以使用以下函数将任何指针作为 unsigned long 获取。 int is not guaranteed to fulfill the task.
int 不能保证完成任务。
template <typename T>
static constexpr inline auto ptrToAddr(T *pointer) noexcept
{
return reinterpret_cast<std::uintptr_t>(pointer);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.