UStruct constantly created when passing through multiple BP (How to prevent copy of struct and just pass pointer)

Hi guys,

Sorry for the long question! Not sure how to explain it well… but I’m in a bit of a bind. I’ve created a UStruct that contains some streaming code to get things from an outside app. Everything is fine and I just have a function in UBlueprintFunctionLibrary that initializes the UStruct properly, which I call in the beginPlay BP of an actor:

.h
UFUNCTION(BlueprintCallable, Category = "MatlabFunctions")
	static FEXT_STREAM CreateExtStream();

.cpp
FEXT_STREAM UMatlabFunctions::CreateExtStream() {
	FEXT_STREAM* stream1;
	stream1 = new FEXT_STREAM();
	return *stream1;
}

So when I run everything, I check with breakpoints and the CreateExtStream only happens once. The problem is when connecting the BP CreateExtStream to the BP AddStringTooSequence, which just gets some info from the external program. The FEXT_STREAM is constantly being created(?)/copied, which means that a new stream is created with the external program on each execution… Dx

.h
UFUNCTION(BlueprintCallable, Category = "MatlabFunctions")
static bool AddStringTooSequence(FEXT_STREAM stream, FString& outputName);

.cpp
bool UMatlabFunctions::AddStringTooSequence(FEXT_STREAM stream, FString& outputName) {

	outputName = stream.doSomething()
	return true;
}

Shouldn’t the stream only be created in the first code, and from that onwards be passed as a pointer, and thus always using the originally created stream, instead of creating a new one always Dx…

Does anyone know how to only have the original struct and then pass it by reference to all other BPs?

Sorry for the long text… :confused:
Thanks!
Cheers

bool UMatlabFunctions::AddStringTooSequence(UPARAM(ref) FEXT_STREAM& stream, FString& outputName)

It didn’t work :confused: AddStringTooSequence still creates a new FEXT_STREAM each time the BP is executed…

Although you can in some cases pass by reference, USTRUCTs are inherently treated as value types by UE4 and there’s not point fighting against this. Your options are to either wrap it inside a UObject (which are always passed by pointer), or to simply make the struct a handle to the underlying data, not actually an instance of it.

You don’t show it, but I’m guessing you’re executing code inside the struct’s constructor? If you show what the struct contains and what its constructor does, it would be easier to say how to go about things.

Either way, you should almost certainly not be creating a USTRUCT on the heap (using new) as you are doing.