Constucting a struct variable in c++

Given a function such as one below

UFUNCTION(BlueprintCallable)
void Func( UStruct* Struct );

How can I construct a struct from the UStruct passed in as parameter? The struct will be passed in from Blueprint.

Edit :
I am trying to construct a struct in the scope of the function as though I am creating a new object, for example, calling

NewObject<SomeObjectClass>( nullptr )

However, even though UStruct is derived from UObject, I cannot use NewObject() to construct a new struct based on the UStruct* param.

I am not sure what you are asking, but I’ll give it a try.
Are you trying to define a new UStruct? Or you have one already?

If you are trying to define a ustruct then on on your .h file add a definition like so:

USTRUCT(BlueprintType)
struct FMyUStruct
{
    GENERATED_BODY()
    UPROPERTY()
    int32 MyInt;
}

then you will have to pass a variable like this to your function:

FMyStruct myStruct;
Func(myStruct);

but the definition must be as follows:

     UFUNCTION(BlueprintCallable)
     void Func( FMyStruct& Struct ); 
    // notice I am using a reference because 
    // pointers to structs are not supported in blueprint

Now, if the function is hardcoded and you already have the struct you should try to cast your pointer:

Cast<UStruct>(myStruct)

but I am not sure that would work. Also you can try a reinterpret_cast()

Take a look at FStructOnScope. This handles creating and initialising a struct instance from a UStruct.

If you need the struct instance to outlive your current scope then you’ll either have to put FStructOnScope into a smart pointer, or copy what it does internally and make it work for what you need.

1 Like

I want to keep my function generic. Thanks for trying though :slight_smile:

Thanks for the prompt reply! Looking at the documentation of FStructOnScope, I do not understand how to access the properties in the struct instance. Is it right of me to assume hat SampleStructMemory is the struct instance? If so, how can I access the properties in the struct instance?

Correct.

The UStruct defines the properties on the struct, and you can use that information to modify the correct memory within the struct instance. FStructOnScope::GetStruct() can get you the UStruct it was created with, and FStructOnScope::GetStructMemory() will get you the instance data.

You’re dealing with completely type-erased data, so you’re reliant on the properties to let you interpret it correctly. See UProperty::ContainerPtrToValuePtr, along with the various forms of ExportText and ImportText that are on UProperty. Property sub-classes also often have extra functions to let you more easily deal with the type of data that the property represents.

You can use TFieldIterator<UProperty> to iterate all the properties on a struct.