How do i run a Console Command in C++

Hi, i saw this thread on how to run a console command via c++, but i want to do something like this.

FString MyCommandString = "r.SetRes ";
FString Resolution = "1920x1080";

FString Final = MyCommandString + Resolution;

GetWorld()->Exec(GetWorld(), TEXT(Final));

but i get horrible errors like ‘LFinal is undefined’ ? where does the ‘L’ come from?
I can’t Execute a var string command :confused: it has to be direct like in the thread above. Any Ideas?

1 Like

Exec() takes in parameter a const TCHAR*. But, TEXT(SomeString) does not perform FString conversion to const TCHAR*. To do this, you have to use the * operator. So, try this instead:

GetWorld()->Exec(GetWorld(), *Final);

TEXT(“some text”) should only be used to make a const TCHAR* for litterals (i.e. defining a string with quotes). Final is a FString, not a litteral. At a lower level, TEXT() adds a L before the litteral, to tell the compiler that the string is in wide char, as described in this page. Example: TEXT(“UE4”) will become L"UE4".

1 Like

GetOwningPlayer()->ConsoleCommand(“StringValue”);

5 Likes

Thnx for that carlitalica. I think exec isnt working because it is expecting a single character. So even when passing it a string its only using the first character. But I havn’t found any more information on UWorld::Exec() yet…

As far as I can tell UWorld::Exec only handles a subset of possible console commands… a very small subset. It seems that APlayerController::ConsoleCommand is the closest to actually typing it into the console. UEngine (GEngine) also has an Exec command that covers a larger set of commands, including forwarding to UWorld::Exec.

So I would argue this answer is misleading and effectively wrong with regard to the question. Though correct with regards to proper use of the TEXT("") macro.

6 Likes

I would recommend using APlayerController::ConsoleCommand if you can easily get the appropriate APlayerController reference.

Using UEngine::Exec via GEngine does seem to cover a large subset of console commands (but not all, as some will need a target and must be routed through the PlayerController in order to find said target).

GEngine->Exec( GetWorld(), TEXT( "stat startfile" ) );
2 Likes

Actually I guess this can work by adding something more.

FProcHandle Proc = FPlatformProcess::CreateProc(*CodeLitePath, nullptr, true, false, false, nullptr, 0, yourworkingdirectory(this must not be empty), nullptr);
	if(Proc.IsValid())
	{
		FPlatformProcess::CloseProc(Proc);
		return true;
	}
	return false;

I can confirm that PlayerController->ConsoleCommand(*cmd) works perfectly