首页 > 解决方案 > Difference between function with returned type pointer and function pointer

问题描述

I have a code with struct defination with member function pointers like this

    struct file_system_type {
        
        struct dentry *(*mount) (struct file_system_type *, int,
                   const char *, void *);
        void (*kill_sb) (struct super_block *);
        
    };

and object of file_system_type like this

    static struct file_system_type minix_fs_type = {
        .mount      = minix_mount,
        .kill_sb    = kill_block_super,
        
    };

and .mount like this

    static struct dentry *minix_mount(struct file_system_type *fs_type,
     int flags, const char *dev_name, void *data)

I like to know what is the difference of above from function with return type some pointer like if I had something like this

    static struct dentry* minix_mount(...)

标签: clinux

解决方案


struct dentry *(*mount) (struct file_system_type *, int,
               const char *, void *);
void (*kill_sb) (struct super_block *);

是具有返回类型的函数的指针struct dentry *void. 首先,您必须为这些指针分配一个实际函数,以通过这些指针调用这些函数。代码中的指针分配有

    .mount      = minix_mount,
    .kill_sb    = kill_block_super,
static struct dentry *minix_mount(struct file_system_type *fs_type,
 int flags, const char *dev_name, void *data)

是一个返回指针的函数。它已经有一个静态函数体,可以立即调用。

两个调用都返回一个具有相同类型的值struct dentry *

函数指针的一大优点是您可以编写通用代码并在运行时为该指针分配不同的函数。常见的用例是诸如排序或查找算法之类的算法,您可以在其中将谓词或比较函数传递给函数指针。

另一个优点是 C 中的结构可以包含函数指针但不能包含函数。这是在 C 中模拟 OOP 的一种方式。

下面是一个函数指针的例子,它指向一个返回指针的函数:

#include <stdio.h>

struct S {
    int x;
    int y;
    // pointers to functions returning a pointer
    int *(*compare1)(int *, int *);
    int *(*compare2)(int *, int *);
};

// functions returning a pointer
int *min(int *a, int *b) {
    return *a < *b ? a : b;
}

int *max(int *a, int *b) {
    return *a > *b ? a : b;
}

int main() {
    struct S s = {
        .x = 5,
        .y = 7,
        .compare1 = &max,
        // .compare2 = &min;
        // name of a function can be used as function pointer
        .compare2 = min
    };
    int *result1 = s.compare1(&s.x, &s.y);
    int *result2 = s.compare2(&s.x, &s.y);
    ++*result1;
    --*result2;
    printf("%d %d", s.x, s.y);
}

输出:

4 8

推荐阅读