question

prxy-4269 avatar image
0 Votes"
prxy-4269 asked RLWA32-6355 commented

Pointer conversion for native 64 application.

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-apic++
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

So has your question been answered?

0 Votes 0 ·

1 Answer

RLWA32-6355 avatar image
1 Vote"
RLWA32-6355 answered RLWA32-6355 commented

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);


· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

What's the solution for such error's ?

0 Votes 0 ·

In the above post is the solution. Cast to ULONG_PTR.

1 Vote 1 ·

You should also read rules-for-using-pointers.

Regarding the functions PtrToLong and PtrToUlong it says "After you convert a pointer variable using one of these functions, never use it as a pointer again. These functions truncate the upper 32 bits of an address, which are usually needed to access the memory originally referenced by pointer."


1 Vote 1 ·