Is there a way to create instance of struct with UScriptStruct

I know that we can use ‘NewObject with UClass*’ to create instance of some class that inherited from UObject like code below.

UClass* ClassType = SomeObject->GetClass();
auto NewInstance = NewObject(this, ClassType);

However I want to create instance of some struct with UStruct(UScriptStruct).
But NewObject function only can be used to create a instance of class inherited from UObject.

Is there a way to do it?
Anyone help me please.

You allocate a new struct same way as in C – just declare it

MyStruct X;
[...fill in the fields in X]
//UScriptStruct* ScriptStruct;

    void* container = FMemory::Malloc(ScriptStruct->GetStructureSize());
    ScriptStruct->InitializeStruct(container);  //init & constructor

    //...
    // manipulate container with reflection data in ScriptStruct
    //...

    ScriptStruct->DestroyStruct(container);  //destructors
    FMemory::Free(container);
1 Like

Sorry for my late reply.
It is that I was really looking for!
Thank you very much Chatouille!

FInstancedStruct is a proper way to do this for runtime. It’s far safer than manually managing the memory yourself and it supports reflection.

Activate the StructUtils plugin to use it.

Wow if that’s the case, FInstancedStruct could be more appropriate way to do this.
I will go over it.
Thank you so much.

If you’re looking for something that doesn’t require a plugin you may be able to use TStructOnScope as well. The major difference is probably that FInstancedStruct is supported by reflection and that the plugin is experimental. But other than that I’m not too familiar with the differences between the two.

https://github.com/EpicGames/UnrealEngine/blob/46544fa5e0aa9e6740c19b44b0628b72e7bbd5ce/Engine/Source/Runtime/CoreUObject/Public/UObject/StructOnScope.h