日期:2014-05-16  浏览次数:20712 次

搞了一年多的c了,第一次看见这样的代码!!!!
下面是linux内核中的一段代码, 我看了半天不明白是什么意思,之前从来没有见过这样调用的,哪位高手能帮忙解释一下下面四行代码究竟是什么意思啊?

C/C++ code
struct ecryptfs_key_mod_ops *(*get_key_mod_ops)(void);
get_key_mod_ops = (struct ecryptfs_key_mod_ops *(*)(void)) dlsym(handle, "get_key_mod_ops");
    
struct ecryptfs_key_mod_ops *(*walker)(void);
walker = builtin_get_key_mod_ops[i];



ecryptfs_key_mod_ops和builtin_get_key_mod_ops的定义如下:
C/C++ code
struct ecryptfs_key_mod_ops {
    int (*init)(char **alias);
    int (*get_gen_key_params)(struct key_mod_param **params,
                  uint32_t *num_params);
    int (*get_gen_key_subgraph_trans_node)(struct transition_node **trans,
                           uint32_t version);
    int (*get_params)(struct key_mod_param **params, uint32_t *num_params);
    int (*get_param_subgraph_trans_node)(struct transition_node **trans,
                         uint32_t version);
    int (*get_blob)(unsigned char *blob, size_t *blob_size,
            struct key_mod_param_val *param_vals,
            uint32_t num_param_vals);
    int (*get_key_data)(unsigned char *key_data, size_t *key_data_len,
                unsigned char *blob);
    int (*get_key_sig)(unsigned char *sig, unsigned char *blob);
    int (*get_key_hint)(unsigned char *hint, size_t *hint_len,
                unsigned char *blob);
    int (*encrypt)(char *to, size_t *to_size, char *from, size_t from_size,
               unsigned char *blob, int blob_type);
    int (*decrypt)(char *to, size_t *to_size, char *from, size_t from_size,
               unsigned char *blob, int blob_type);
    int (*destroy)(unsigned char *blob);
    int (*finalize)(void);
};

static struct ecryptfs_key_mod_ops *      //这个定义是傻意思啊?也请高手帮忙解答一下噢
(*builtin_get_key_mod_ops[])(void) = {
    &passphrase_get_key_mod_ops,
    NULL
};


------解决方案--------------------
四行中的前两行:定义函数指针,把dlsym的返回值强制转换为同类型函数赋给该函数指针。
后两行:定义函数指针,并为该函数指针赋值。
下面代码中:定义一个函数指针数组,数组的每个元素就是一个函数地址。
好复杂
上Demo code:
C/C++ code

#include <stdio.h>

int add(int a, int b)
{
    return a + b;
}

int sub(int a, int b)
{
    return a - b;
}

/* its return value is a function pointer */
int (*fun_p(void))(int, int)
{
    return add;
}

int main(void)
{
    int (*calc)(int, int);    /* function pointer */
    int (*fun_p_arr[2])(int, int) = { &add, &sub };    /* function pointer array, just like the last five-lines code */

    int a = 3, b = 4;

    calc = fun_p();        /* just like the first two line of your four-lines code */
    printf("Add: %d\n", calc(a, b));

    calc = fun_p_arr[1];    /* just like the last two line of your four-lines code */
    printf("Sub: %d\n", calc(a, b));

    return 0;
}