#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); 替换
它仍然有效吗?是因为在 C 中,如果我传递一个方法,它会将它还原为指向该方法的指针吗?还是因为 CreateThread(NULL, 0, &Main, NULL, 0, NULL);
; 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
sizeof
operator 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/