art vanderlay
art vanderlay

Reputation: 2463

in C is a lookup table a replacement for variable variables like in bash||php

In Bash I would use variable variables to store the name of a variable or pointer so I could use it in a different function. Is a lookup table the correct replacement in C?

My problem is I have created two variables/objects in

source_A.

frameRate_1 = gst_caps_new_simple ("video/x-raw",
               "framerate", GST_TYPE_FRACTION, 25, 1,  
          NULL);
frameRate_2 = gst_caps_new_simple ("video/x-raw",
               "framerate", GST_TYPE_FRACTION, 60, 1,  
          NULL);

In Source B, I read parameters from fileOne.cfg that has the name of the variable\object to load for the correct parameters, this is the name of the variable\object to use from source_A.

fileOne.cfg

frameRate_2

source_B

//....Load parameter into variable  
// useThisFrameRate=frameRate_2
applyFrameRate(&useThisFrameRate);

This name is then passed to a function in source_C that will use the name to reference the variable/object from source_A.

source_C

applyFrameRate (char *useThisFramerate){
g_object_set( G_OBJECT ( name ),  "caps",  *useThisFramerate, NULL );
}

Reading the MAN pages and some explanations I can see how lookup tables can be used to store and reference static and dynamic variables, but I could not see how to reference a variable name using the lookup tables and pass this as a reference.

Or am I over thinking this and should I be using & somehow to get to the name object by reference?

Upvotes: 0

Views: 246

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

I could not see how to reference a variable name using the lookup tables and pass this as a reference

That is because C does not provide such mechanism. In fact, once the compiler is done with your code, variable names do not exist, except in debug symbol files, which are not part of your program anyway.

To use look-up tables with names, you need to maintain name lists yourself. For example, you could make a parallel array of names to look up configuration values, and use its index to reference an array of frame rates:

const char *frConfig[] = {"frameRate_1", "frameRate_2", "frameRate_3"};
GstCaps *frLookup[] = {frameRate_1, frameRate_2, frameRate_3};

Now you can do look-up like this:

GstCaps *lookupByName(const char *name) {
    for (int i = 0 ; i != sizeof(frConfig)/sizeof(frConfig[0]) ; i++) {
        if (strcmp(frConfig[i], name) == 0) {
            return frLookup[i];
        }
    }
    return NULL; // Not found
}

Upvotes: 1

Related Questions