【问题标题】:C - the typedef function used as a pointer in the argument of another function [duplicate]C - 在另一个函数的参数中用作指针的 typedef 函数[重复]
【发布时间】:2015-07-28 06:58:56
【问题描述】:

我有一个头文件定义了一些代码如下所示:

typedef uint8_t EnrollT(uint16_t test1, uint16_t test2);
typedef void ChangeT(uint64_t post1, uint8_t post2);

struct ClusterT * ClientAlloc(EnrollT *, ChangeT *);

我有以下问题:

  1. 下面的代码是否相等?

    typedef uint8_t EnrollT(uint16_t test1, uint16_t test2);
    typedef uint8_t (*EnrollT)(uint16_t test1, uint16_t test2);
    
  2. 在包含此标头的 C 文件中,如何在 ClientAlloc 函数中处理这两个参数?示例代码对我来说很棒。

================================================ ==========================

感谢您的回复。 通过拥有两个真正的函数,我将它们传递给以下代码:

ClientAlloc(Enroll, Change)

但是,当我编译代码时,出现以下错误,这里有什么遗漏吗?

expected declaration specifiers or ‘...’ before ‘Enroll’
expected declaration specifiers or ‘...’ before ‘NotifyChange’

【问题讨论】:

  • @SouravGhosh,您介意再解释一下吗?
  • 在第一个语句中,您正在为uint8_t 创建一个别名,在第二个语句中,您正在创建一个函数指针。
  • 为了您的更新,我们需要查看那些函数定义——或者,至少,函数定义的签名部分。您的代码提到“更改”,错误消息提到“通知更改”;这使我们认为在您写信给 SO 之前正在进行一些编辑。如果您要这样做,请确保我们无法发现您正在这样做!
  • @JonathanLeffler 我不完全确定这是那个问题的重复......它的第二部分似乎可能会问更多......但没关系。
  • @Freenode-newbostonSebivor:有很多可能的替代副本:Understanding typedefs for function pointers; Typedeffing a function (NOT a function pointer); How do function pointers in C work;我敢肯定还有其他可能性。

标签: c function-pointers typedef


【解决方案1】:

不,他们不是。

typedef uint8_t (*PEnrollT)(uint16_t test1, uint16_t test2);

定义与此签名匹配的函数指针类型。所以,

uint8_t EnrollT(uint16_t test1, uint16_t test2);

与此签名匹配 你可以像这样使用: PEnrollT pfn = EnrollT; 并用作 pfn(..); // 相当于调用 EnrollT

现在,你有

typedef uint8_t EnrollT(uint16_t test1, uint16_t test2);
typedef void ChangeT(uint64_t post1, uint8_t post2);

因此,您的 EnrollT 类型是“具有两个 uint16_t 参数返回 uinit8_t 的函数。 另外,你有,

struct ClusterT * ClientAlloc(EnrollT *, ChangeT *);

所以,如果你有两个函数匹配 EnrollT、ChangeT,你可以调用 ClientAlloc 传递这两个函数

【讨论】:

  • 您似乎在第二个示例中省略了typedef
  • @Jana,对于我的第二个问题,您的意思是“ClientAlloc(enroll, change);”吗?这正如甘甘迪在答案中写的那样?
  • @user3815726,是的,但是您需要有两个与这些签名匹配的真实函数,然后传递这两个真实函数
  • @DebasishJana,谢谢。我刚刚更新了我的问题,如果您有任何想法,请回复。
【解决方案2】:

解决第二个问题:

您必须使用 EnrollT 和 ChangeT 定义的签名创建两个函数(但不能按名称使用类型 EnrollT 和 ChangeT):

uint8_t enroll(uint16_t test1, uint16_t test2){ ... };
void change(uint64_t post1, uint8_t post2){ ... };

然后将它们传递给函数调用:

ClientAlloc(enroll, change);

【讨论】:

  • 欢迎来到 StackOverflow。我想你可能误解了这个问题......
  • 这是对本文第二个问题的回应。这有什么问题?
  • @gandgandi,谢谢。我刚刚更新了我的问题,如果您有任何想法,请回复。
猜你喜欢
  • 1970-01-01
  • 2016-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-19
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
相关资源
最近更新 更多