use*_*915 -2 c++ memory pointers
在 C++ 中,使用 iostream,您可以打印变量的内存地址。例如:
std::cout << &variable << std::endl;
// Example Result: 002AFD84
Run Code Online (Sandbox Code Playgroud)
但是,如果我想将此内存地址存储到变量中怎么办?比如把内存地址转换成字符串或者double(或者int等)?或者甚至将该字符串或双精度(或整数等)再次转换回内存地址?
I'd like to do this for various reasons, one being: This would allow me to return the memory address for data within a DLL to a program calling the DLL and it's functions. On top of this, I won't have to keep track of the data itself within the DLL, since the data could then be referenced by it's memory address.
I cannot use pointers in this particular situation due to constraints. The constraints being: The interpreted programming language I am using does not have access to pointers. Due to this, pointers cannot be used to reference the data outside of the DLL.
As a side question, what number format do memory addresses use? They seem to always seems to be 8 characters in length, but I can't figure out what format this is.
To convert a pointer into a string representation, you can use a string stream. These are similar to the standard I/O streams std::cin
and std::cout
, but write to or read from a string rather than performing I/O.
std::ostringstream oss;
oss << &variable;
std::string address = oss.str();
Run Code Online (Sandbox Code Playgroud)
To convert a pointer into an integer that represents the same address, use reinterpret_cast
. The type uintptr_t
, if it exists, is guaranteed to be large enough to hold any pointer value. But I think usually it suffices to use unsigned long
.
unsigned long address = reinterpret_cast<unsigned long>(&variable);
Run Code Online (Sandbox Code Playgroud)
Converting a pointer into a floating-point type seems fairly useless. You would have to convert into an integral type first, then convert to a floating-point type from there.