How to get UObject* from void* using UClass*

As the title says, I’d like to get UObject* value from void* value. The only information about the pointer is UClass object.

As you already know, this code is not compileable:

void* voidPtr;
UObject* objPtr = Cast<UObject>(voidPtr);

And this code will compile but might cause misbehave:

(see c++ - Conversion from void* to the pointer of the base class - Stack Overflow)

void* voidPtr;
UObject* objPtr = (UObject*)voidPtr;

Any ideas if there are methods like

void* voidPtr;
UClass* someClass;
UObject* objPtr = someClass->Get(voidPtr);

Thanks for your interest

Hi,

Does your void* definitely represent a UObject*? And not an interface pointer of a UObject, or a non-UObject? If so, you could do this:

UObject* Ptr = ((UObject*)voidPtr)->IsA(someClass) ? (UObject*)voidPtr : nullptr;

i.e. Ptr will be a pointer to an object of type someClass (or subclass), or nullptr if it is not of that type.

If your void* does not definitely point to a UObject* then there is no way of achieving what you are after.

Steve

Yes, the void* must be a UObject derived class pointer.

Actually what I want to achieve is getting a interface pointer from this void ptr.
And after some inspection to UClass code, I found there are interfaces array and there are the offset value to the interface pointer. I added that value to the ptr and and get working interface now.

A simpler way would be:

ISomeInterface* iface = Cast<ISomeInterface>((UObject*)data);

Steve

code is like this:

void* data = ~~~;
for (auto& it : staticClass->Interfaces)
{
    if (it.Class->IsChildOf(USomeInterface::StaticClass())
    {
        ISomeInterface* iface = reinterpret_cast<ISomeInterface*>(reinterpret_cast<uint8*>(data) + it.PointerOffset);

        // I can use the iface now
    }
}