Possible to make TArray point to existing allocated memory without copying?

Dear Unreal Engine community!

Is it possible to make a TArray point to existing memory instead of allocating new memory?

For example, if there already exists some C-style array (i.e. uint8* SomeArray), and I know the number of elements, is there a way to make a TArray<uint8> of this length, and just use that pointer as the Data of the TArray? I would like to avoid copying memory an extra time, but I need this data to be a TArray type for some convenient things it offers.

Any help or advice would be appreciated. Thank you.

Hello! You can try to use that

	TArray<int32> a = { 1,2,3 };
	TArray<int32> b(a.GetData(), a.Num());
	TArray<int32> c(a);

Also, it is rather common to use FMemory::Memcpy to quickly copy memory blocks in C style

Thank you for the comment! I looked through the existing constructors for TArray and found these, but they seem to be copy constructors, unless a TArray&& r-value reference is used (which I don’t have as it’s simply a c-style pointer to memory). I also found the MoveOrCopy methods, that can sometimes move, but they seem to also require a TArray.

I currently Memcpy in the code I’m using, but my end goal is not having to copy at all, as the data is quite large, so it’s unnecessary and less performant.

This whole process is used to convert data imported from disk by a third-party C++ library into Unreal-specific types, and I could only make the C-style array to TArray conversion work with Memcpy, which is not ideal.

Maybe Memmove could work, but I’m a little afraid to do so since I’m not entirely sure it’s safe to do.

Ok… One possible thing that might help you - you can just read values directly in TArray to avoid copy (read num of elements, create TArray, set num, GetData to get raw pointer and then read from disk to raw pointer)… But of course this is only if num is stored at the beginning of disk data, that is often true for C style read/write routines