Pointer conversion for native 64 application.

prxy 61 Reputation points
2021-06-24T11:50:08.187+00:00

Hello,

Below code works fine on 32bit platform but crashed for 64bit platform.

#include <iostream>
#include<string>
#include<Windows.h>
using namespace std;
class CStroageClass
{
    std::string name; 
    int number;
public: 
    CStroageClass(): name("prxy"), number(20)
    {

    }
    void PrintName() { std::cout << "name:" << name << std::endl; }
    void PrintNumber() { std::cout << "number:" << number << std::endl; }
};

int main()
{
    CStroageClass * obj = new CStroageClass;
    cout << obj << std::endl;

    unsigned long  ul = PtrToUlong(obj);

    std::cout << "UL:" << ul << std::endl;

    CStroageClass* so = reinterpret_cast<CStroageClass*>(ULongToPtr(ul));
    cout << so << std::endl;
    so->PrintName();
    so->PrintNumber();

    return 0;
}

How to resolve such error's ?

Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,523 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,636 questions
{count} votes

Accepted answer
  1. RLWA32 43,306 Reputation points
    2021-06-24T12:09:30.483+00:00

    When you build for 64 bits the PtrToUlong function returns a truncated 32 bit value which cannot be converted back to a valid 64-bit pointer. The source for ULongToPtr contains this warning - "Caution: ULongToPtr() zero-extends the unsigned long value." That is why round-tripping is problematic.

    Try this -

        ULONG_PTR  ul = (ULONG_PTR) obj;
    
        std::cout << "UL:" << ul << std::endl;
    
        CStroageClass* so = reinterpret_cast<CStroageClass*>(ul);
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful