传递函数是否通过引用传递?

#include <windows.h>

DWORD WINAPI Main(LPVOID lpParam) {
    MessageBox(0,"Hello World from DLL!\n","Hi",MB_ICONINFORMATION);
    return S_OK;
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
    switch(fdwReason) {
        case DLL_PROCESS_ATTACH:
        DisableThreadLibraryCalls(hinstDLL);
        CreateThread(NULL, 0, &Main, NULL, 0, NULL);
        break;

        case DLL_PROCESS_DETACH:
        break;

        case DLL_THREAD_ATTACH:
        break;

        case DLL_THREAD_DETACH:
        break;
    }

    return TRUE;
}

为什么我可以替换CreateThread(NULL,0,& Main,NULL,0,NULL);使用CreateThread(NULL,0,Main,NULL,0,NULL);它还能运作吗?是因为在C中,如果我传递一个方法,它会将它减少为指向该方法的指针吗?或者是因为DWORD是一个指针?

最佳答案 >从技术上讲,在C中,一切都是通过值传递的,而不是通过引用传递的.当指针作为参数传递时,它看起来像通过引用传递.

>最有可能的DWORD被定义为一个整数,它在机器上有两个单词的大小.

>函数名称会自动转换为编译器指向函数的指针.

C99 §6.3.2.1 Lvalues, arrays, and function designators

A function designator is an expression that has function type. Except when it is the
operand of the sizeofoperator or the unary &operator, a function designator with
type ‘‘function returning type’’ is converted to an expression that has type ‘‘pointer to
function returning type’’.

此外,你可以使用*指向函数的指针,你得到函数指示符作为结果.使用它,你可以稍微玩一下:

#include <stdio.h>

typedef void (*func_ptr)(void);
void foo(void)
{
    printf("hello\n");
}

int main(void)
{
    func_ptr p;
    p = &foo;   //function pointer
    p();
    p = foo;    //function name is converted to function pointer
    p();
    p = *foo;   //legal
    p();
    p = *****************foo;  //still legal
    p();
    return 0;
}

输出:

hello
hello
hello
hello
点赞