【问题标题】:Understanding C struct理解 C 结构
【发布时间】:2015-05-20 16:43:22
【问题描述】:

我试图了解以下 C 结构中发生了什么:

/* EXCERPT from LINES 59-90 */
/* parse.h
 * Copyright (c) 2011, Peter Ohler
 * All rights reserved.
 */

typedef struct _ParseInfo {
    // used for the string parser
    const char      *json;
    const char      *cur;
    const char      *end;
    // used for the stream parser
    struct _Reader  rd;

    struct _Err     err;
    struct _Options options;
    VALUE       handler;
    struct _ValStack    stack;
    CircArray       circ_array;
    int         expect_value;
    VALUE       proc;
    VALUE       (*start_hash)(struct _ParseInfo *pi);
    void        (*end_hash)(struct _ParseInfo *pi);
    VALUE       (*hash_key)(struct _ParseInfo *pi, const char *key, size_t klen);
    void        (*hash_set_cstr)(struct _ParseInfo *pi, Val kval, const char *str, size_t len, const char *orig);
    void        (*hash_set_num)(struct _ParseInfo *pi, Val kval, NumInfo ni);
    void        (*hash_set_value)(struct _ParseInfo *pi, Val kval, VALUE value);

    VALUE       (*start_array)(struct _ParseInfo *pi);
    void        (*end_array)(struct _ParseInfo *pi);
    void        (*array_append_cstr)(struct _ParseInfo *pi, const char     *str, size_t len, const char *orig);
    void        (*array_append_num)(struct _ParseInfo *pi, NumInfo ni);
    void        (*array_append_value)(struct _ParseInfo *pi, VALUE value);

    void        (*add_cstr)(struct _ParseInfo *pi, const char *str, size_t len, const char *orig);
    void        (*add_num)(struct _ParseInfo *pi, NumInfo ni);
    void        (*add_value)(struct _ParseInfo *pi, VALUE val);
} *ParseInfo;

来自https://github.com/ohler55/oj/blob/master/ext/oj/parse.h#L59

我不明白第 74 行(上面清单中的第 22 行)发生了什么。

开始于:

    VALUE       (*start_hash)(struct _ParseInfo *pi);

有人能解释一下这些行在做什么吗?

【问题讨论】:

  • 这些是函数指针声明。 stackoverflow.com/questions/840501/…
  • 在这里发布代码。链接会随着时间的推移而失效。
  • 不是他的代码,是版权。
  • 不严格。我要编辑。

标签: c pointers struct function-pointers forward-declaration


【解决方案1】:

它们是function pointers,语法是:return-type (*pointer_name)(args)

但是,开发人员使用了一种特殊的技术,由第一个参数表示,它始终是指向 _Parser 结构的指针。它确实允许一种简单的面向对象编程形式,其中类可以具有专门作用于某个对象实例的方法,但这些方法必须手动设置和处理。 @paxdiablo 的优秀答案here 中的更多信息。

注意:有多个违反 ISO C 的规定,因为您不能在名称前加上 _ 和大写名称。更多信息here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    相关资源
    最近更新 更多