开发者

Compatibility between 2 structs

I wish I could just use the preprocessor, but the input comes at runtime.. I tryed a conditional typedef, doesn't work. Or conditional declaration, doesn't work. Although I didn't really expect them to neither. And since all the code that follows is the exact same, I don't want to have to rewrite it twice.. once for each struct.

Is there a way to do this in C? Or different approach, with same result. All my google searches brought me to C++ templates. If I'm not being clear, maybe this will help:

#include <stdio.h>

struct a32 {
    short bits;
    unsigned long val;
    // more values, not necessarily in the same order
};

struct a64 {
    short bits;
    unsigned long long val;
    // etc...
};

int main(void) {
    struct a32 mystruct;

    // read mystruct from somewhere

    if(mystruct.bits == 64) {
        // th开发者_JAVA技巧en I need mystruct to be a64
        // re-read mystruct
    }

    // exact same code for both structs

    printf("%d\n", sizeof(mystruct.val));
    return 0;
}

Any help would be appreciated.


Why not do something like this, assuming that padding won't be an issue:

struct {
    unsigned long val;
} a32;

struct {
    unsigned long long val;
} a64;

int main(void) {
    short bits;
    union {
        struct a32 struct32;
        struct a64 struct64;
    };

    // Read bits

    if (bits == 64) {
        // Read into struct64
    } else {
        // Read into struct32
    }

    return 0;
}

This will, of course, require you to be aware of the value of bits so you know which struct variable to access.


You can "sorta" do this using unions:

struct{
    short bits;
    union{
        unsigned long a32;
        unsigned long long a64;
    };
} a_int;

int main(void) {
    a_int mystruct;

    // read mystruct from somewhere

    if(mystruct.bits == 64) {
        // then I need mystruct to be a64
        // re-read mystruct
    }

    // exact same code for both structs

    printf("%d\n", sizeof(mystruct.a32));
    return 0;
}

EDIT: However, it's not possible to make the printf() work for both the 32-bit and 64-bit integers.


Not 100% sure this is what you mean. If not, please clarify the question.

You should use a tagged union. Make a struct with a tag (e.g. an int) and a union. The union is between the possible structs that this could be, and the tag identifies which one in particular it is.

Google "tagged union" for more details.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜