具有:

struct packet_sample_t {
   int common_id;
   int some;
   char data[];
   float foo;
}


具有以下功能:

void dispatch_packet(void *packet);


我的目标是解析数据包ID,然后调用其处理程序,但我无法从common_id检索结构变量void *

我想用高级语言创建类似interface的东西,假设我所有的数据包结构都应具有变量common_id
所以我正在寻找可以像下面这样工作的东西:

struct packet_base {
   int common_id;
}

void dispatch_packet(void *packet) {
   int common_id = ( (packet_base *)packet )->common_id;
   switch(common_id) {...}
}

void test() {
   packet_sample_t packet = {.common_id = 10, ...};
   dispatch_packet((void *) &packet); //this function should retrieve `common_id`

   packet_other_t other = {.common_id = 1};
   dispatch_packet((void *) &other); // again with another packet
}


我对C语言不太熟悉,我真的不知道该怎么做。但是用简单的话来说,我希望能够将一个数据包强制转换为它的packet_base,它们共享一个公共变量。

编辑:示例中的更多详细信息

最佳答案

您的技术有效。有a number of ways to do struct inheritance in C,这是其中之一。 21st Century CObject-Oriented Programming with ANSI C可能都是一本好书。

您在声明和使用结构和类型时遇到问题。让我们看看这个。

struct packet_base {
   int common_id;
};


其类型为struct packet_base。如果要声明此类型的指针,则需要编写struct packet_base *packet。如果要转换此类型的变量,则为(struct packet_base *)thing

这很烦人,因此通常使用typedef为结构声明类型别名。语法为typedef <type> <alias>

typedef struct {
   int common_id;
} packet_base_t;


也就是说,类型struct { int common_id; }别名为packet_base_t。现在,您可以使用packet_base_t作为类型。 packet_base_t *packet声明一个指针,而(packet_base_t *)thing强制转换。

修复该问题,再加上一些小错误,它可以工作。有关char *datachar data[]的信息,请参见What is the difference between char array vs char pointer in C?

typedef struct {
   int common_id;
   int some;
   char *data;
   float foo;
} packet_sample_t;

typedef struct {
   int common_id;
} packet_base_t;

void dispatch_packet(void *arg) {
    // It's simpler to cast to a new variable once then to muck
    // up the code with casts.
    packet_base_t *packet = (packet_base_t *)arg;

    int common_id = packet->common_id;
    printf("id: %d\n", common_id);
}

关于c - C泛型继承,详细程度较低,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50915953/

10-11 23:23
查看更多