views:

99

answers:

2

In regards to C what is a stub routine? Also an example would be much appreciated as well.

+4  A: 

It is a function with the same signature as the real function but it does nothing, and can be compiled and executed just like the real thing. e.g.

int MyStub(char * str)
{
    /* Stub - Does Nothing */

    return 0;
}

These are often used as placeholders, so that overall program structure can be worked out first, and then the details.

Mitch Wheat
+7  A: 

A stub routine can be one of (at least) two things.


First, it can be a place-holder routine which you quickly develop to test a higher level routine, with the intention of substituting a real version later on. This is typically used with top-down development (coding the higher levels first then working your way down to the more detailed stuff) and can be as simple as:

int getCount (void) { return 7; } // just return fixed value for testing.

or slightly more complex:

// Cycle through values for some variety.
int getCount (void) {
    int retvals[] = {2,7,1,8,2,8,1,8,2,8,4,5,9};
    static int pos = -1;
    pos = (pos + 1) % (sizeof (retvals) / sizeof (*retvals));
    return retvals[pos];
}

Of course, once the stub gets complex enough, you may as well just implement the real thing :-)


Secondly, it's commonly used in remote procedure call (RPC) environments. A stub there is used for marshalling data at one end and communicating it to a server at the other end.

RPC needs to create stub functions for the client and a server. It's very similar to a function prototype in C but the end result is slightly different, such as:

+----------------+
| Client         |
|  +----------+  |  +---------------+
|  |   main   |  |  | Server        |
|  |----------|  |  |  +----------+ |
|  | stub_cli |------->| stub_svr | |
|  +----------+  |  |  |----------| |
+----------------+  |  | function | |
                    |  +----------+ |
                    +---------------+

In this example, instead of calling function in the same program, main calls a client stub function (with the same prototype as function) which is responsible for packaging up the information and getting it across the wire to another process. This can be the same machine or a different machine, it doesn't really matter - one of the advantages of RPC is to be able to move servers around at will.

In the server, there's a 'listener' process that will receive that information and pass it to the server. The server's stub receives the information, unpacks it and passes it to the real function.

The real function then does what it needs to and returns to the server stub which can package up the return information and pass it back to the client stub.

The client stub then unpacks that and passes it back to main.

paxdiablo
Awesome answer, thanks a bunch :)
Dustin