How do I implement this code?

I found some c++ code online and I want to implement it. I have a render target, I know how to create a c++ class and kind of know c++, but don’t know how to implement the code.

void AMyActorClass::CopyRTTextureToArray(UTextureRenderTarget2D* Texture, TArray<FColor>& Array)
{
    if (Texture->GetFormat() != PF_B8G8R8A8) {
        UE_LOG(LogTemp, Log, TEXT("Texture format should be PF_B8G8R8A8 (Displacement)"));
        return;
    }

    struct FCopyBufferData {
        UTextureRenderTarget2D* Texture;
        TPromise<void> Promise;
        TArray<FColor> DestBuffer;
    };
    using FCommandDataPtr = TSharedPtr<FCopyBufferData, ESPMode::ThreadSafe>;
    FCommandDataPtr CommandData = MakeShared<FCopyBufferData, ESPMode::ThreadSafe>();
    CommandData->Texture = Texture;
    CommandData->DestBuffer.SetNum(Texture->SizeX * Texture->SizeX);

    auto Future = CommandData->Promise.GetFuture();

    ENQUEUE_RENDER_COMMAND(CopyTextureToArray) (
        [CommandData](FRHICommandListImmediate& RHICmdList)
        {
            auto Texture2DRHI = CommandData->Texture->GetResource()->GetTexture2DRHI();
            uint32 DestPitch{ 0 };
            uint8* MappedTextureMemory = (uint8*)RHILockTexture2D(Texture2DRHI, 0, EResourceLockMode::RLM_ReadOnly, DestPitch, false);

            uint32 SizeX = CommandData->Texture->SizeX;
            uint32 SizeY = CommandData->Texture->SizeX;

            FMemory::Memcpy(CommandData->DestBuffer.GetData(), MappedTextureMemory, SizeX * SizeY * sizeof(FColor));

            RHIUnlockTexture2D(Texture2DRHI, 0, false);
            //signal completion of the operation
            CommandData->Promise.SetValue();
        }
        );

    // wait until render thread operation completes
    Future.Get();
    Array = std::move(CommandData->DestBuffer);
}

When I try to implement the code myself i keep getting a pointer error.

The code is already implemented… what you don’t know is how to use it…

But… this are pointers

here

here

here

They are not UObject so check all them using nullptr

if(MyPointer==nullptr)
{
     //invalid pointer
     return;
}

When you find the NULL punter then you need allocate memory for it…

i think the NULL pointer can be this
UTextureRenderTarget2D* Texture

but check all them anyway

This Array need a size too

TArray<FColor>& Array

the size is this

SizeX * SizeY * sizeof(FColor)

i’m not sure if Array = std::move(CommandData->DestBuffer); do this job or not… but i think not…
If not you need resize it before pass it to the function.

In other hand you have a asynchronous function… it can cause pointers problems too.
Make sure the code is bloking here untill the job is done!!

  // wait until render thread operation completes
    Future.Get();

Best regards!!

2 Likes