我正在使用posix_memalign
(在 align_alloc
方面遇到麻烦)分配(在我自己的 new
内),所以我有一个 void*
。我需要它作为 int 例如来计算对齐:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main() {
void *ptr;
auto align{4096}, size{10000};
posix_memalign( &ptr,align,size );
cout << ptr << endl; // works
cout << ptr % align << endl; // not
return 0;
}
我用现代 C++ 思考 static_cast<long>
这将是正确的方法,但这会产生一个错误,即void*
上不允许这样做。那么正确的方法是什么呢?我当然可以使用旧式的 C 类型转换,但我正在努力避免这些。
最佳答案
您不能将指针static_cast
指向非指针类型。您可能必须使用reinterpret_cast
:
reinterpret_cast<long>(ptr);
此外,由于您希望获取整数形式的指针地址,因此最好使用 stdint.h
中存在的 intptr_t
(为此目的而设计):
reinterpret_cast<intptr_t>(ptr);
关于c++ - 从 void* 到 long 的正确转换是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58415323/