0

I have a small myTest.exe file. I opened this in a text editor and copied the text.

std::string exeBinaryCode = "Copied text from exe";

Now I want that when I passed this string to the system(exeBinaryCode) then it will execute and give the same result that myTest.exe gives.

If anyone knows how to achieve this, please post the answer.

codeling
  • 11,056
  • 4
  • 42
  • 71
  • I presume that since you have a .exe file that you're on Windows, so you should probably remove the `unix` tag – Jan Apr 13 '22 at 06:32
  • The `system()` call needs the name of the executable, not its binray code. Please read its documentation. – the busybee Apr 13 '22 at 06:41
  • Basically, a C *string* (don't know about C++) can only have one single `'\0'` byte. You can get around that "limitation", but you no longer have a *string*. – pmg Apr 13 '22 at 06:51
  • @pmg `std::string` can have `\0` in the middle, though its not common and one has to be careful with functions that expect it to be null terminated – 463035818_is_not_an_ai Apr 13 '22 at 07:38

1 Answers1

0

To begin with, executable files are binary files. You can't open them in text editors, or copy/paste them as text, or store them in a string variable.

(That last part isn't 100% true, since std::string basically just stores a string of bytes that don't necessarily have to be text, but you really shouldn't use it as such.)

There are a few different ways to achieve similar results, which you choose depends on what you're actually trying to accomplish.

Notice that none of these include directly running the binary data. Though there may be some obscure system call that allows you to do that you'll likely end up with loads of trouble (anti-virus, incompatibility across platforms, etc.).

Refer to the external executable by path

Simplest, just pass the path to the executable to system. If you intend to distribute your application you'd just package the external executable as well (so if you have your own code compiled into bin/myapp.exe in a zip-file you'd also have bin/whatineedtocall.exe in the same zip).

Unless you have very specific requirements this is what I'd recommend.

Use your build system to embed the data and write it to the file system

Some build systems and frameworks (for example CMake, see Embed resources (eg, shader code; images) into executable/library with CMake) have the ability to embed binary data such as executables into code. You can then, in your code, write this binary data to the file system when it is needed (preferably into some temporary location) and run it from there using system.

Embed as hexadecimal data and write to file system

Similar to the previous, but you can also insert the contents into your code manually. Note that you'd need to copy the executable binary not from a text editor, but in it's hexadecimal representation (see the previously linked question for examples, you'd want to end up with pretty much the same file).

Jan
  • 993
  • 1
  • 13
  • 28