c 结构将自身作为参数传递给指针函数

标签 c struct pic xc16

我正在尝试创建一个具有嵌套函数的结构,它将结构本身作为参数传递到嵌套函数中,以简化调用函数。该代码将使用 xc16 编译器在 Pic 24f 系列 MCU 上运行。另外,我知道 count 函数是多余的,但我认为它说明了我的观点。例如:

结构:

typedef struct
{
    uchar Fifo[UART1_RX_MAX_BUFFER_SIZE];
    uchar FifoIndex = 0;
    uchar FifoCount = 0;
    uchar FifoOverrunFlag = FALSE;
    uchar (*CountPointer);
    uchar (*PutPointer);
}Fifo;

功能:

// Returns: The number of items in the Fifo
uchar FifoGetCount(Fifo *fifo)
{
    return fifo->FifoCount;
}

// Summary: Adds data to the end of the Fifo
// Parameters:  
//          data: Data to be added to the end of the Fifo
// Returns: True (1) if the data was successfully added
//      False (0) if the data was not successfully added
//          as a result of the Fifo being full
uchar FifoPut(Fifo *fifo, uchar data)
{
    if (fifo->FifoCount > FIFO_MAX_SIZE)
    {
        fifo->FifoOverrunFlag = TRUE;
        return FALSE;
    }
    uint putIndex = fifo->FifoGetPutIndex();
    fifo->Fifo[putIndex] = data;
    fifo->FifoCount++;
    return TRUE;
}

主要:

Fifo fifo1;

int main()
{
    fifo1.CountPointer = FifoGetCount(fifo1);
    fifo1.PutPointer = FifoPut(fifo1, uchar data);

    // Intended Usage
    uchar myCount = fifo1.FifoGetCount();
    uchar myData = 1;
    fifo1.FifoPut(myData);
}

最佳答案

请注意,uchar (*PutPointer); 只是一种有趣的编写 uchar *PutPointer; 的方式。要创建函数指针,您必须编写: uchar (*PutPointer)(…); 其中 应替换为函数类型的规范参数——原型(prototype)。

由于您有一个函数uchar FifoPut(Fifo *fifo, uchar data),因此您似乎应该编写:

typedef struct Fifo Fifo;

struct Fifo
{
    uchar Fifo[UART1_RX_MAX_BUFFER_SIZE];
    uchar FifoIndex = 0;
    uchar FifoCount = 0;
    uchar FifoOverrunFlag = FALSE;
    uchar (*CountPointer)(Fifo *fifo);
    uchar (*PutPointer)(Fifo *fifo, uchar data);
};

然后,在 main() 中,您可以编写:

fifo1.CountPointer = FifoGetCount;
fifo1.PutPointer = FifoPut;

这会将函数指针 FifoGetCountFifiPut 分配给结构体的元素。您已将通过调用该函数一次生成的 uchar 值分配给 uchar * 的代码。这应该会生成编译器警告。如果是的话,你应该在你的问题中这么说。如果不是,您需要打开相关的编译器警告,或者获取更好的编译器。

然后您可以将该函数用作:

uchar myCount = fifo1.FifoGetCount(&fifo1);
uchar myData = 1;
fifo1.FifoPut(&fifo1, myData);

请注意,您必须显式地将结构体的地址作为第一个参数传递给函数; C 编译器不会神奇地为你做这件事。如果您希望隐式完成此操作,那么您正在寻找的语言称为 C++。

关于c 结构将自身作为参数传递给指针函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24225028/

相关文章:

c - 数组循环写入元素 C

c - 退出时是否应该释放分配的内存?

C++ 增量运算符

包含 unsigned char 和 int 错误的 C++ 结构

c - 二叉树和快速排序?

c - strcpy() 创建错误

c - 使用嵌入式C中的指定初始化程序初始化结构。“期望表达式”

c - 从文件的特定部分读取 PIC32MX

clang - 如何告诉 clang 我的 LLVM 目标应该使用 16 位 'int'?

c - 使用 pic16 从 eeprom 中读取数据