Mark
Mark

Reputation: 1309

C++ - evaluating an input string as an internal code variable

Is there a way to take a string as an input argument to a c++ function and evaluate it as an internal argument e.g. the name of a structure or other variable?

For example (written in pseudo code)

int myFunction(string nameStructure){ nameStructure.field = 1234 }

The "take away" point is converting the input string as a variable within the code.

Mark

Upvotes: 0

Views: 70

Answers (3)

alcedine
alcedine

Reputation: 949

The names of local variables are just artifacts of the human-readable code and have no meaning in the compiled binary. Your int myIntVar's and char* myCharP's get turned into instructions like "four bytes starting at the location of the base pointer minus eight bytes, interpreted as a four-byte integer". They no longer have names as such.

Upvotes: 1

Nikola Dimitroff
Nikola Dimitroff

Reputation: 6237

This type of question is often a symptom of a XY problem so consider other options first. That being said, there's no such default mechanism in C++ but there is a simple workaround I can think of - use a dictionary (std::map / std::unordered_map) to store all your objects:

std::map<std::string, MyAwesomeObject> objects;
...
int myFunction(std::string nameStructure)
{
    objects[nameStructure].field = 1234
}

Upvotes: 5

Krab
Krab

Reputation: 6756

If you export symbols from your binary, you can at runtime to look into export table according to your binary format and find the variable you want. But i bet you want something like access to local variable and that is not possible.

If you really need this funcionality, take a look at more dynamic interpreted languages as php

http://php.net/manual/en/language.variables.variable.php

Upvotes: -1

Related Questions