Convert Tarray(int32) to Tarray(int16)

one way is to iterate the array and do sth like a = (int16)b, any way to avoid iteration?

TArray is a native array wrapper and way arrays work in C++ is you get pointer and what is inside [] is just memory address offset, this means if you would cast int32* to int16* you would mess up indexing as array would read address offset per 16-bits not 32-bit, so you would get 2 halfs of of 32-bit integer bits, you would need to read every 2nd index.

It is possible as you can access pointer to native array which contains data

You could cast it but then remember to read every 2nd index.

Keep native C/C++ arrays are super low level, technically it not even a array as this is valid feature to all pointers of all types, there no sense of size (C++ expect you to track that, that why C++ standard library and UE4 got it’s own array implementation in first place to make it easier, C++ nativly only does that for statically declared arrays), you can even offset backward by putting minus index. Reading outside array range will give you trash results as you start to read some random variables, there also potential of hitting unallocated space and crash, so watch out what you doing. Also don’t write anything in to it as it will desync TArray array tracking and mess up the array and if you can also corrupt memory if you write it wrong. TArray can reallocation (bit don’t need to) when you resize the array (or else you do Reserve TArray::Reserve | Unreal Engine Documentation) so pointer may change and you need to get new one from GetData()

Coping would require iteration and don’t think you can fix it, it is something CPU would need to support and it only support address to address coping without any conversion with copy instructions:

https://en.wikibooks.org/wiki/X86_Assembly/Data_Transfer

In C++ you do that via memcpy

TArray use those instructions to quick copy array and reallocation without iteration

1 Like