• Advertisement
Sign in to follow this  

Pointer to variables from its name

This topic is 4060 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I would like to know how I could get the pointer to a variable in a class, by only providing the name of the variable to the class. This variable could have any type… For example, I would like a function that would look like : void* GetPointerfromName(char*) Thank you !

Share this post


Link to post
Share on other sites
Advertisement
if (name == "abc")
{
return reinterpret_cast<void*>(&this->abc);
}
else if (name == "zzyy")
{
return reinterpret_cast<void*>(&this->zzyy);
}
else ...

Share this post


Link to post
Share on other sites

Thank you, but wouldn't be there a more generic implementation ?

I saw something like :
template <class T> T const * GetAddress(const T& value);

Any idea ??

Share this post


Link to post
Share on other sites
What's the context? Can you describe in more detail what you're trying to do?

Share this post


Link to post
Share on other sites
Yep,

I try to create a class of Interface between a dll and a program. I would like the program to get the address of any public variable inside a class of my dll only by giving its name. I want to be able to add or delete variables for programming without changing the function that calls the variables.

Actually, I don't even know if it is possible.

Share this post


Link to post
Share on other sites
template<typename T>
T* MyClass::GetPointerfromName(MyClass::*T var)
{
return &(this->*var);
}

int main()
{
int* p = my_obj.GetPointerfromName(&MyClass::x);
};
or
template<typename T>
T* MyClass::GetPointerfromName(const std::string& name)
{
std::map<std::string, boost::any> name_map = boost::list_of_map_begin
("abc", &MyClass::abc)
// .....
("xyz", &MyClass::xyz);

std::map<std::string, boost::any>::iterator i = name_map.find(name);
if (i == name_map.end())
{
throw std::logic_error("Member does not exist");
}

return &(this->*(boost::any_cast<MyClass::*T>(*i)));
}

int main()
{
int* p = my_obj.GetPointerfromName<int>("xyz");
}

Share this post


Link to post
Share on other sites
While this is an overkill, it is a somewhat interesting way to add reflection and run-time created classes.

http://www.vollmann.ch/en/pubs/meta/meta/meta.html

If anything, it at least makes for interesting reading.

Share this post


Link to post
Share on other sites
The offsetof macro can do this, but this is probably not a good idea. Just pass around some sort of dictionary. Or, hell, if all you want is to not modify code that doesn't use the new parameter, but still needs to pass it on for some reason, pass a struct.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement