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

标签 c function function-pointers

#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 是一个指针?

最佳答案

  1. 从技术上讲,在 C 语言中,一切都是按值传递的,而不是按引用传递的。当指针作为参数传递时,它看起来就像通过引用传递。
  2. 很可能 DWORD 被定义为一个整数,其大小为机器上的两个单词。
  3. 编译器会自动将函数名称转换为指向函数的指针。

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

关于c - 传递函数是否通过引用传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19473330/

相关文章:

c - ARM v4 从调用 SWI 的 C 函数返回存储在 r0 中的值

c - 利用缓冲区溢出

c - 在 c 奇怪的行为中添加两个数字

function - erlang 改变一个有趣的环境

c++ - 迭代和调用元组内的异构函数

c - c中的pf apply是什么?

c - 在没有 Autotools 的情况下使用 C 单元测试框架检查?

c++ - 对我书中的练习感到困惑

c++ - 与 C++ 中的 virtual 关键字混淆

c++ - C++中如何实现指向成员函数的指针?