有人可以告诉我,在知道 union 是全局队列结构的成员的情况下,如何使用写入函数保留分配给 union 成员的值?
基本上我所做的就是定义一个数据队列缓冲区结构,其中包含队列名称、长度和互斥体(用于读写函数之间的同步)。缓冲区数据是不同系统的内务结构体;使用 union 来封装所有不同的结构。为每个系统(eps_q、com_q 等)创建了队列结构的不同实例。
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
typedef union qbuf{
eps_hk eps_buf[EPS_HK_SIZE];
odb_hk odb_buf[ODB_HK_SIZE];
com_hk com_buf[COM_HK_SIZE];
cam_hk cam_buf[CAM_HK_SIZE];
adcs_hk adcs_buf[ADCS_HK_SIZE];
}qbuf_t;
typedef struct {
qbuf_t qbuf;
int qwindex;
int qlength;
int qfull;
char *qname;
pthread_mutex_t *qmut;
pthread_cond_t *qFull;
}queue;
queue *odb_q;
queue *eps_q;
queue *com_q;
queue *cam_q;
queue *adcs_q;
/*************************************************/
/**** read and write functions in eps.c *****/
int eps_queueAdd (queue *q, eps_hk hk)
{
q->qbuf.eps_buf[q->qwindex] = hk;
printf(".... After queue add..... vbatt %u\n", q->qbuf.eps_buf[q->qwindex].vbatt);
q->qwindex++;
if (q->qwindex == q->qlength) {
q->qwindex = 0;
q->qfull=1;
}
return (q->qfull);
}
eps_hk eps_queueRead(queue *q) //read hk from local eps hk table, for hk handlers
{
eps_hk hk;
sleep (10);
hk = q->qbuf.eps_buf[q->qwindex];
printf(".... INSIDE queue read .....vbatt %u \n", q->qbuf.eps_buf[q->qwindex].vbatt);
return (hk);
}
写入函数 (queueADD) 工作得很好。这里的问题是,当我尝试读取之前使用 (queueADD) 写入的值(比方说 10)时,我似乎找不到它(我得到 0 )。
感谢您花时间阅读我的帖子 =)
===编辑============================================ =====================
我在队列结构中使用 union 的目的是为不同的数据类型定义一个通用队列。当然,我考虑过使用 void* 指针,但内存分配和指针取消引用太麻烦了。你觉得怎么样?
最佳答案
您需要队列中的一个枚举来告诉您 union 体的哪个成员被选择。示例:
typedef enum
{
qbuf_select_eps = 0;
qbuf_select_odb;
qbuf_select_com;
qbuf_select_cam;
qbuf_select_adcs;
}qbuf_select_t;
typedef struct {
qbuf_t qbuf;
qbuf_select_t qbuf_select;
int qwindex;
int qlength;
int qfull;
char *qname;
pthread_mutex_t *qmut;
pthread_cond_t *qFull;
}queue;
在函数中你可以像这样使用 switch 。
queue *q;
...
switch (q->qbuf_select)
{
case qbuf_select_eps:
//Operations on q->qbuf.eps_buf
break;
case qbuf_select_com:
//Operations on q->qbuf.com_buf
break;
...
}
我使用了这个解决方案并且工作正常。
关于c - 如何在 C 中的函数调用之间保留 union 成员的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56187844/