mardi 24 mai 2016

C++ - Using a variable without knowing what it is called

I have a program that uses plug-ins. As I'm in development, these plug-ins are currently just .h and .cpp files that I add or remove from my project before re-compiling, but eventually they will be libraries.

Each plug-in contains lists of data in vectors, and I need to dynamically load data from the plug-ins without knowing which plug-ins are present. For instance:

// plugin1.h

extern vector<int> plugin1Data;

// plugin2.h

extern vector<int> plugin2Data;

// main.cpp

vector<vector<int>> pluginDataList;

int CountPlugins () {

    // Some function that counts how many plug-ins are present, got this bit covered ;)
}

int main() {

    int numPlugins = CountPlugins();

    for (int i = 0; i < numPlugins; i++) {

        vector<int> newPluginData = /***WAY TO ADD PLUGIN DATA!!!***/;

        pluginDataList.push_back(newPluginData);
    }
}

I already access the names of each plugin present during my CountPlugins() function, and have a list of names, so my first gut feeling was to use the name from each plugin to create a variable name like:

vector<string> pluginNames = /*filled by CountPlugins*/;

string pluginDataName = pluginNames.at(i) + "Data";

// Use pluginDataName to locate plugin1Data or plugin2Data

That's something I've done before in c# when I used to mess around with unity, but I've read a few stackoverflow posts clearly stating that it's not possible in c++. It's also a fairly messy solution in C# anyway as far as I remember.

If each plugin was a class instead of just a group of vectors, I could access the specific data doing something like plugin2.data... but then I still need to be able to reference the object stored within each plugin, and that'll mean that when I get round to compiling the plugins as libraries, I'll always have to link to class declaration and definition, which isn't ideal (though not out of the question if it'll give a nicer solution over all).

I'm all out of ideas after that, any help you can offer will be most welcome!

Thanks! Pete

Aucun commentaire:

Enregistrer un commentaire