开发者

Is it possible to imitate python tuples in C?

I am just curious to know 开发者_开发知识库what are the strategies ? (If the strategies exists).


A typical pattern in C for implementing an object that can hold one of a number of different basic types is to use a struct containing one element which is a union of the possible basic types that can be stored, and one element which is an enum identifying which of those types the union is being used for in this case.

Then you could use an array of such objects, perhaps represented as a struct containing a number of items, and a pointer to the storage for those items.

e.g. something like this:

#include <stdio.h>
#include <stdlib.h>

typedef enum tuple_datatype_e {
    TUPLE_DATATYPE_INT,
    TUPLE_DATATYPE_FLOAT,
    TUPLE_DATATYPE_STRING
} tuple_datatype_t;

typedef struct tuple_item_s {
    tuple_datatype_t datatype;
    union {
        int   int_val;
        float float_val;
        char *string_val;
    } u;
} tuple_item_t;

typedef struct tuple_s {
    unsigned int n_items;
    tuple_item_t *items;
} tuple_t;

static void print_tuple(tuple_t *t)
{
    unsigned int i;

    printf("(");
    for (i = 0; i < t->n_items; i++) {
        if (i > 0)
            printf(", ");
        switch (t->items[i].datatype) {
        case TUPLE_DATATYPE_INT:
            printf("%d", t->items[i].u.int_val);
            break;
        case TUPLE_DATATYPE_FLOAT:
            printf("%f", t->items[i].u.float_val);
            break;
        case TUPLE_DATATYPE_STRING:
            printf("\"%s\"", t->items[i].u.string_val);
            break;
        }
    }
    printf(")\n");
}

int main(void)
{
    tuple_t foo;

    foo.n_items = 3;
    foo.items = malloc(sizeof(tuple_item_t) * foo.n_items);
    foo.items[0].datatype = TUPLE_DATATYPE_INT;
    foo.items[0].u.int_val = 123;
    foo.items[1].datatype = TUPLE_DATATYPE_FLOAT;
    foo.items[1].u.float_val = 4.56;
    foo.items[2].datatype = TUPLE_DATATYPE_STRING;
    foo.items[2].u.string_val = "789";
    print_tuple(&foo);

    return 0;
}


The closest to Python tuples in C is probably either structs or arrays, depending on how you will use them.

Use structs if you want to group a fixed number of related values of possibly different types.

Use arrays if you want a number of values of the same type and the ability to index into the array.


Although not exactly the same, a const array has at least some of the same properties. If you require more exact emulation, an ADT could do the trick.


There the LinuxTuples in C with an API

http://linuxtuples.sourceforge.net/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜