[Last Call] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 690
  • Last Modified:

access c++ method using string literal


I have a problem I am working on here. I wish to store in a file a list of attributes for an object. From within a C++ class i then want to read in this file and access the specified attributes for the object.

the file might say - type, a Get method name and a Set method name.
int, GetID, SetID

somewhere there is a class like
class MyClass
int m_ID;
int GetID() {return m_ID;};
void SetID(int val) {m_ID = val;};

then in the code i wish to get this row from the file and execute the correspoding Get or Set method on the object.

string gettype = get the type from the file
string getmethod = get the Get method name from the file
string setmethod = get the Set method name from the file

then somehow say

class MyClass obj = new class MyClass();

*** this is the bit i haven't a clue about
int result = (gettype) obj.getmethod();

is this possible? or even ignore the typing.

any help gratefully appreciated.

2 Solutions
No, it's not possible--unless you build it all yourself, or do a lot of very arcane, difficult, and implementation-specific magic with a debug build of the program.

As an example of building it all yourself, you could design the class with a function that takes a member name string and returns a value, along with a function that takes a member name string and a value and stores the value.

There are other languages that would make this much easier than it would be in C++.  Python is one.

  As efn said, you'd have to implement this yourself.  What your looking for is a combination of reflection & persistence of some kind.  Java can do this, but standard C++ cannot do this.  One way to do this is use interfaces like COM does, but that still requires knowledge of the interface.
   I am working on a library to do persistence, but it is a long way from being usuable.  I came up with a way to do something like this, but it doesn't really use gets/sets.  There is another possibility if you don't mind using the boost libary (boost.org).  First you define an interface that all classes must support which need to do this:

struct OOData {

    virtual std::map<std::string, boost::any> getFields()=0;
    virtual bool setFields(std::map<std::string, boost::any>)=0;

   The object whose attritubutes are being stored fill the map, and then still need to figure out how to determine the type and cast it to the type to be stored in the file.  The loading function/class would build a map of the atrritubes and their values (stored in any) and pass it to the object using setFields.

   Because of the nature of map, be sure to check to see if the string exists in the map first.  Otherwise, you'd just create a map to a new value for that string.  Then you can access the fields using the strings.  You need to cast it back to its value.

   That's the basic idea.  You would not be using the proper OO way of using gets & sets, but this allows a bit of abstraction for the concerns (the persistence of the attritributes & logic of the program).  This way also opens your options up if you decide to later store the attributes in a database.  If done right, you shouldn't have to change a lot of the code in the logic part.  Implementing some type of reflection probably is not worth it in my opinion.  I didn't give you everything, but I think I might have set you on a good path to follow.
jaygeekayAuthor Commented:
"What your looking for is a combination of reflection & persistence of some kind."

Yup, I want to be able to serialize an object but I want to be able to configure what within the object actually needs to be serialized. JSON was mentioned here as a possible solution, but I can't find any examples of how i would do this anywhere.

Are there any solutions out there for doing something like this?
Thanks for your replies, Jim.

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  I am not sure what you mean by JSON.  Could you describe it further?  
   Let me see if I understand you correctly.  You want a mechanism to specify what will be serialized to the storage medium, and you want to decide what will not be serialized.  Setting asside possible unitialized object concerns, the object being serialized knows what needs to be serialized.  So, it needs to be in control.  I think you need to read http://www.microsoft.com/msj/archive/S385.aspx it probably doesn't give you all the answers you want, but it should give you some ideas.
   I am writing a library to allow you to do something similar to what you talked about, BUT it is nowhere ready for anyone else to look at.
C++ needs to know the member names in advance, so such operations are not supported.  It would be possible to write some code that interprets the inidividual lines in the file:

if ( sFirstToken=="nID" ) {
    objCur.nID= GetNextTokenAsInt();
if ( sFirstToken=="sStringValue" ) {
    objCur.sStringValue= GetNextTokenAsString();


Here's a screwball possiblity:  You can use the windows scripting support... and for instance, JScript supports the

    eval( string_of_jscript_source_code )

fn.  So that would allow you to have a line in the file like:

    objCur.AnyNameHere= "the value for it";

your code could read in a series of such lines and eval() each of them.  When done, objCur would have all of its members variables populated (at least the ones that were saved when the file was serialized and/or edited manually).  Then you would need a system to transfer data from the JavaScript environment to populate the object in the C++ program.  I guess that part might be about as hard as doing the item-by-item interpretter...  It would never have the flexibility of JScript -- for instance, you can't add member variables to a C++ object at runtime.

Or you could design your C++ objects for total flexibility... no "real" (named) data members, just a single map of variable names to variable values.  Then you would need to access each data member using the contrived syntax like an ADO recordset:

    int nID= objCur.GetValueFor("nID");

>> I want to be able to configure what within the object actually needs to be serialized.

The standard C++ solution is to just serialize the entire object.  If there is some reason why you can't do that, you can make the first item a set of flags or instructions to direct the serializing and deserializing operational code.  If you goal is to make it easy to edit the object with a text editor, there is nothing that says you can't serialize everyting to string values and add commentary labels in the stream and end each object with "\r\n"

-- Dan
jaygeekayAuthor Commented:
Thanks folks for your replies.
There was a small bit more work in the end than I had envisaged.
Some of it along the lines of what was suggested above.

For the configuration side - I associate an id with each attribute. I'm not sure yet whether this will be a simple int or a more descriptive string. I have a configuration file which specifies the ids to serialise.

At the moment I create a structure on construction of the object which associates each id with a memory pointer. So when serialising it is a simple task of moving the data in/out of the pointed to space. Note that the structure contains a union to allow for different types. I'm not sure if this is really necessary though. It might be easier to do as Dan suggested.

Then the serialisation - well, simple types are easy enough to serialise, but each class dependency also needs to be serialised. And also vectors/queues etc. At the moment my solution is very simple. Any class that wishes to be serialised must implement it's own serialise/deserialise method. Arrays/queues etc. will have to store the size and then serialise each entry.

For my first foray into serialising it is certainly an eye opener.

Anyways, as I said, thanks for your replies.

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now