“(datatype)(* ptrname)(datatype)”是什么意思?

问题描述 投票:0回答:2

1)我目前正在尝试理解以下代码,但我无法理解void(* func)(void)意味着什么,我可以理解我正在尝试从list0513保存名为“function”的函数的地址,在void指针func,但是在等号之前的转换(void)意味着什么?

// list0513.c
#include <dlfcn.h>
int main(void)
{       
    void *handle = dlopen("./list0513.so", RTLD_LAZY);
    void (*func)(void) = dlsym(handle, "function");
    (*func)();
    dlclose (handle);
    return 0;
}    

根据该书,从以下脚本调用称为“函数”的函数

// list0513dl.c
#include <stdio.h>
void function(void)
{
    printf("Hello World\n");
}

2)但如何制作list0513.so文件?我制作的唯一文件是.c文件...感谢您阅读本文。

c linux dll
2个回答
0
投票

声明内容如下:

       func           — func
      *func           — is a pointer to
     (*func)(    )    — a function taking
     (*func)(void)    — no parameters
void (*func)(void)    — returning void

然后使用func调用的结果初始化dlsym指针,该调用返回库”function中函数list0513.so的地址。

指针类型的一般声明规则:

T *p;       // p is a pointer to T
T *p[N];    // p is an array of pointer to T
T (*p)[N];  // p is a pointer to an array of T
T *f();     // f is a function returning a pointer to T
T (*f)();   // f is a pointer to a function returning T

在声明和表达式中,后缀[]下标和()函数调用操作符的优先级高于一元*,因此*f()被解析为*(f())(函数返回指针)。要声明指向数组或函数的指针,必须使用数组或函数声明符显式地组合*

声明可能变得非常复杂 - 您可以拥有一系列指向函数的指针:

T (*a[N])(); // a is an array of pointers to functions returning T

或函数返回指向数组的指针:

T (*f())[N]; // f is a function returning a pointer to an array

甚至指向函数指针数组的指针返回指向数组的指针:

T (*(*(*a)[N])())[M];

你可能不会在野外看到任何毛茸茸的东西(除非你碰到我的一些旧代码)。


-1
投票

它省略了函数类型的声明。完整版或扩展版应该是这样的:

// list0513.c
#include <dlfcn.h>
int main(void)
{       
    void *handle = dlopen("./list0513.so", RTLD_LAZY);
    typedef void(*FUNC)();
    FUNC func = dlsym(handle, "function");
    func();     // call function
    dlclose (handle);
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.