How to convert the address stored in the string to void* in c++

Friends,


I have a address stored in string, I would like to convert back to original object, something like below

Test& GetObject(string obj_address)
{
const void * address = static_cast<const void*>(obj_address);
return (Test&)address;
}

obj_address has a value like '000000000018FB74', i'm not able to convert this string to void*, static_case uses the address of that string, not the value of that string.

Please help me to convert to void* from the address stored in the string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
#include <type_traits>

// assumes that the address stored in the string is valid and is in hex
// assumes that T is an (optionally cv-qualified) object type or void
template < typename T = const void > T* as_pointer_to( const std::string& address )
{
    static_assert( std::is_object<T>::value || std::is_void<T>::value, "invalid type" ) ;

    // http://en.cppreference.com/w/cpp/string/basic_string/stoul
    const unsigned long long value = std::stoull( address, nullptr, 16 ) ; // may throw
    return reinterpret_cast< const T* >(value) ;
}

int main()
{
    const std::string str = "000000000018FB74" ;
    
    const void* pv = as_pointer_to<const void>(str) ;
    std::cout << pv << '\n' ;
    
    const int* pi = as_pointer_to<const int>(str) ; 
    std::cout << pi << '\n' ;
}

http://coliru.stacked-crooked.com/a/f80774e55cc7310a
Awesome. Thanks a lot. its working.
Topic archived. No new replies allowed.