Trying to write function that returns an array from Object using it's variable name passed as a string. (Basic Knowledge of C++)

I am trying to write a function that can return an array which is a variable from an object by accessing it directly using a string of it’s variable name. The reason I want to do this is because the Object in question has hundreds of variables and I don’t want to drag each variable out to get them manually. I want to look them up by their name using a string.

I found a function online that can get an int by string name:

int UMyBlueprintFunctionLibrary::GetIntByString(UObject* object, FString variableName, bool& found)
{
FName nameOfProperty = FName(variableName);
UClass
objectclass = object->GetClass();
UProperty* Property = objectclass->FindPropertyByName(nameOfProperty);
if (Property)
{
UNumericProperty* NumericProperty = Cast(Property);
if (NumericProperty)
{
UIntProperty* IntProperty = Cast(NumericProperty);
if (IntProperty)
{
void* ValuePtr = IntProperty->ContainerPtrToValuePtr(object);
found = true;
return NumericProperty->GetSignedIntPropertyValue(ValuePtr);
}
}
}
found = false;
return 0.0f;
}

This works great and I can get all the integer variables I want just by using the string name.

However, I now want to do the same thing but for an array of integers. Here’s what I have so far;

TArray UMyBlueprintFunctionLibrary::GetIntArrByString(UObject* object, FString variableName, bool& found)
{
FName nameOfProperty = FName(variableName);
UClass
objectclass = object->GetClass();
UProperty* Property = objectclass->FindPropertyByName(nameOfProperty);
if (Property)
{
UArrayProperty* ArrProperty = Cast(Property);
if (ArrProperty)
{
found = true;
}
}
found = false;
return TArray{0};
}

This returns true but that’s it. I have tried but can’t figure out how to return an array from my object because I have a very basic understanding of C++ especially inside UE4.

Any help in finishing this function would be greatly appreciated.

1 Like

This is not documented.
Search engine source code for examples, you are looking for FScriptArrayHelper and its method GetRawPtr

Example:

TArray<TSharedPtr<FJsonValue>> FPropertyToJSON(FArrayProperty* Property, const UObject* Container)
{
    auto ArrayPtr = Property->ContainerPtrToValuePtr<void>(Container);

    FScriptArrayHelper Helper(Property,ArrayPtr);

    for (int32 i = 0, N = Helper.Num()-1; i <= N; i++)
    {
		auto Value = FJsonObjectConverter::UPropertyToJsonValue(Property->Inner, Helper.GetRawPtr(i), 0, CPF_Transient);
    }
}
2 Likes

Ah brilliant! Thanks very much this looks like what I need. :+1: