mardi 3 novembre 2020

How to get Object^ from pointer address?

I want to get Object^ from pointer address in clr/c++.

The address type is unsigned long long, its a pointer to pointer.

There is Microsoft demo code (full project):

// removed some unnecessary code

// a pointer
void* m_impl;

// get a pointer to SomeClass
void GetClassPointer(){
    SomeClass ^ obj = gcnew SomeClass();
    m_impl = GCHandle::ToIntPtr(GCHandle::Alloc(obj)).ToPointer(); 
}

// do something by pointer
void DoSomething(){
    GCHandle h = GCHandle::FromIntPtr(IntPtr(m_impl));
    SomeClass ^ obj = safe_cast<SomeClass^>(h.Target);
    // do something
    obj->DoSomething();
}

I tried this code:

// Address Type
typedef unsigned long long UINT_PTR;

// a pointer
void * ptr;

// address is a pointer to SomeClass*
void GetClassPointer(UINT_PTR address){
    // I also tried "ptr = (void*)address;"
    ptr = *(void**)address;
}

void DoSomeThing(){
    GCHandle h = GCHandle::FromIntPtr(IntPtr(ptr));
    SomeClass ^ obj = safe_cast<SomeClass^>(h.Target);
    // do something
    obj->DoSomeThing();
}

It is always error in line

GCHandle h = GCHandle::FromIntPtr(IntPtr(ptr));

What is the correct way to get Object^ from pointer address?





Aucun commentaire:

Enregistrer un commentaire