小话mfc

Q1: HINSTANCE到底表示什么?

A: 如果从数据类型来解释,它仅仅是指针的一种形式;对于操作系统来说,一个运行的程序就可以被看成一个这种类型的句柄。

  1. typedef void __RPC_FAR *HINSTANCE;
typedef void __RPC_FAR *HINSTANCE;
类似地,还有其它一些H开头的类型:
  1. typedef void __RPC_FAR *HANDLE;
  2. typedef void __RPC_FAR *HMODULE;
  3. typedef void __RPC_FAR *HRGN;
  4. typedef void __RPC_FAR *HTASK;
  5. typedef void __RPC_FAR *HKEY;
  6. typedef void __RPC_FAR *HDESK;
  7. typedef void __RPC_FAR *HMF;
  8. typedef void __RPC_FAR *HEMF;
  9. typedef void __RPC_FAR *HPEN;
  10. typedef void __RPC_FAR *HRSRC;
  11. typedef void __RPC_FAR *HSTR;
  12. typedef void __RPC_FAR *HWINSTA;
  13. typedef void __RPC_FAR *HKL;
  14. typedef void __RPC_FAR *HGDIOBJ;
typedef void __RPC_FAR *HANDLE;

typedef void __RPC_FAR *HMODULE;

typedef void __RPC_FAR *HRGN;

typedef void __RPC_FAR *HTASK;

typedef void __RPC_FAR *HKEY;

typedef void __RPC_FAR *HDESK;

typedef void __RPC_FAR *HMF;

typedef void __RPC_FAR *HEMF;

typedef void __RPC_FAR *HPEN;

typedef void __RPC_FAR *HRSRC;

typedef void __RPC_FAR *HSTR;

typedef void __RPC_FAR *HWINSTA;

typedef void __RPC_FAR *HKL;

typedef void __RPC_FAR *HGDIOBJ;


可以看出,void *就是它们的本质。



Q2: 操作系统操作一个内核对象为什么使用句柄,而不使用真实的指针?

A: 这个问题其实就像,为什么去银行取钱需要通过ATM取款机而不是把一大把钞票放在你面前让你去取。

操作系统如果暴露指针,程序员可能很容易倾向于对于指针内部数据的存取,而这很可能破坏整个结构。所以,抽象出一个句柄来,更安全。

另外,内核对象一般需要采用引用计数来避免因为意外释放导致其它使用它的程序崩溃,所以这也要求需要对内核对象进行封装,句柄应运而生。

NT内核内部调用ob模块的ObReferenceObjectByHandle函数来实现句柄到指针的转换:

  1. NTSTATUS
  2. ObReferenceObjectByHandle ( //从句柄找到地址
  3. __in HANDLE Handle,
  4. __in ACCESS_MASK DesiredAccess,
  5. __in_opt POBJECT_TYPE ObjectType,
  6. __in KPROCESSOR_MODE AccessMode,
  7. __out PVOID *Object,
  8. __out_opt POBJECT_HANDLE_INFORMATION HandleInformation
  9. )
NTSTATUS
ObReferenceObjectByHandle ( //从句柄找到地址
    __in HANDLE Handle,
    __in ACCESS_MASK DesiredAccess,
    __in_opt POBJECT_TYPE ObjectType,
    __in KPROCESSOR_MODE AccessMode,
    __out PVOID *Object,
    __out_opt POBJECT_HANDLE_INFORMATION HandleInformation
    )
具体内部的转换过程这里不详细介绍,详情请参考深入windows操作系统。



Q3: wsprintf和swprintf函数怎么这么像?

A: 我认为这是ms设计不当的一个实例。如此相近的函数只会让程序员更容易犯错,如下是两者的原型。

  1. WINUSERAPI int WINAPIV wsprintfA(LPSTR, LPCSTR, ...);
  2. WINUSERAPI int WINAPIV wsprintfW(LPWSTR, LPCWSTR, ...);
  3. #ifdef UNICODE
  4. #define wsprintf wsprintfW
  5. #else
  6. #define wsprintf wsprintfA
  7. #endif // !UNICODE
  8. _CRTIMP int __cdecl swprintf(wchar_t *, const wchar_t *, ...);
WINUSERAPI int WINAPIV wsprintfA(LPSTR, LPCSTR, ...);
WINUSERAPI int WINAPIV wsprintfW(LPWSTR, LPCWSTR, ...);
#ifdef UNICODE
#define wsprintf  wsprintfW
#else
#define wsprintf  wsprintfA
#endif // !UNICODE


_CRTIMP int __cdecl swprintf(wchar_t *, const wchar_t *, ...);

由上,wsprintf改为sprintf_t或者tsprintf更好点。



Q4: 为什么在默认情况下wprintf(L"%s", L"你好"); 会输出乱码?

A: 这都是locale惹的祸,如果没有它,这个函数或许可以保证正常输出。加载c运行时库将设置默认的Locale为"C", wprintf函数内部会调用WideCharToMultiByte函数将宽字符转换成多字节字符,而这个过程,不是使用操作系统本机语言的locale,而是使用locale "C"的(它是由TLS数据得到的).

如果是简体中文操作系统,添加如下语句,输出即可正常:

  1. setlocale(LC_ALL, "chs");
setlocale(LC_ALL, "chs");

对于setlocale参数中语言可选择的值,可以参考: http://msdn.microsoft.com/zh-cn/library/39cwe7zf(v=vs.110).aspx



Q5: SelectObject和DeleteObject函数是做什么的?

A: 它们不是一个多么通用的函数,只是对于GDI绘制过程中的绘图对象进行选择和删除的函数。

  1. __gdi_entry WINGDIAPI HGDIOBJ WINAPI SelectObject(__in HDC hdc, __in HGDIOBJ h);
__gdi_entry WINGDIAPI HGDIOBJ WINAPI SelectObject(__in HDC hdc, __in HGDIOBJ h);
  1. __gdi_entry WINGDIAPI BOOL WINAPI DeleteObject( __in HGDIOBJ ho);
__gdi_entry WINGDIAPI BOOL WINAPI DeleteObject( __in HGDIOBJ ho);

这两个函数名都不好,我认为改为SelectGDIObj和DeleteGDIObj更合适。

命名同样不太好的函数还有:GetObject, GetStockObject, SetWindowLong等函数.



Q6: AfxMessageBox和MessageBox有什么区别?

A: 先看看源代码:

  1. int AFXAPI AfxMessageBox(LPCTSTR lpszText, UINT nType, UINT nIDHelp)
  2. {
  3. CWinApp* pApp = AfxGetApp();
  4. if (pApp != NULL)
  5. {
  6. return pApp->DoMessageBox(lpszText, nType, nIDHelp);
  7. }
  8. else
  9. {
  10. return CWinApp::ShowAppMessageBox(NULL, lpszText, nType, nIDHelp);
  11. }
  12. }
int AFXAPI AfxMessageBox(LPCTSTR lpszText, UINT nType, UINT nIDHelp)
{
	CWinApp* pApp = AfxGetApp();
	if (pApp != NULL)
    {
		return pApp->DoMessageBox(lpszText, nType, nIDHelp);
    }
	else
    {
		return CWinApp::ShowAppMessageBox(NULL, lpszText, nType, nIDHelp);
    }
}
CWinApp的ShowAppMessageBox的内部实现如下:
  1. // Helper for message boxes; can work when no CWinApp can be found
  2. int CWinApp::ShowAppMessageBox(CWinApp *pApp, LPCTSTR lpszPrompt, UINT nType, UINT nIDPrompt)
  3. {
  4. // disable windows for modal dialog
  5. DoEnableModeless(FALSE);
  6. HWND hWndTop;
  7. HWND hWnd = CWnd::GetSafeOwner_(NULL, &hWndTop);
  8. // re-enable the parent window, so that focus is restored
  9. // correctly when the dialog is dismissed.
  10. if (hWnd != hWndTop)
  11. EnableWindow(hWnd, TRUE);
  12. // set help context if possible
  13. DWORD* pdwContext = NULL;
  14. DWORD dwWndPid=0;
  15. GetWindowThreadProcessId(hWnd,&dwWndPid);
  16. if (hWnd != NULL && dwWndPid==GetCurrentProcessId() )
  17. {
  18. // use app-level context or frame level context
  19. LRESULT lResult = ::SendMessage(hWnd, WM_HELPPROMPTADDR, 0, 0);
  20. if (lResult != 0)
  21. pdwContext = (DWORD*)lResult;
  22. }
  23. // for backward compatibility use app context if possible
  24. if (pdwContext == NULL && pApp != NULL)
  25. pdwContext = &pApp->m_dwPromptContext;
  26. DWORD dwOldPromptContext = 0;
  27. if (pdwContext != NULL)
  28. {
  29. // save old prompt context for restoration later
  30. dwOldPromptContext = *pdwContext;
  31. if (nIDPrompt != 0)
  32. *pdwContext = HID_BASE_PROMPT+nIDPrompt;
  33. }
  34. // determine icon based on type specified
  35. if ((nType & MB_ICONMASK) == 0)
  36. {
  37. switch (nType & MB_TYPEMASK)
  38. {
  39. case MB_OK:
  40. case MB_OKCANCEL:
  41. nType |= MB_ICONEXCLAMATION;
  42. break;
  43. case MB_YESNO:
  44. case MB_YESNOCANCEL:
  45. nType |= MB_ICONQUESTION;
  46. break;
  47. case MB_ABORTRETRYIGNORE:
  48. case MB_RETRYCANCEL:
  49. // No default icon for these types, since they are rarely used.
  50. // The caller should specify the icon.
  51. break;
  52. }
  53. }
  54. #ifdef _DEBUG
  55. if ((nType & MB_ICONMASK) == 0)
  56. TRACE(traceAppMsg, 0, "Warning: no icon specified for message box.\n");
  57. #endif
  58. TCHAR szAppName[_MAX_PATH];
  59. szAppName[0] = '\0';
  60. LPCTSTR pszAppName;
  61. if (pApp != NULL)
  62. pszAppName = pApp->m_pszAppName;
  63. else
  64. {
  65. pszAppName = szAppName;
  66. DWORD dwLen = GetModuleFileName(NULL, szAppName, _MAX_PATH);
  67. if (dwLen == _MAX_PATH)
  68. szAppName[_MAX_PATH - 1] = '\0';
  69. }
  70. int nResult = MessageBox(hWnd, lpszPrompt, pszAppName, nType);
  71. // restore prompt context if possible
  72. if (pdwContext != NULL)
  73. *pdwContext = dwOldPromptContext;
  74. // re-enable windows
  75. if (hWndTop != NULL)
  76. ::EnableWindow(hWndTop, TRUE);
  77. DoEnableModeless(TRUE);
  78. return nResult;
  79. }
// Helper for message boxes; can work when no CWinApp can be found
int CWinApp::ShowAppMessageBox(CWinApp *pApp, LPCTSTR lpszPrompt, UINT nType, UINT nIDPrompt)
{
	// disable windows for modal dialog
	DoEnableModeless(FALSE);
	HWND hWndTop;
	HWND hWnd = CWnd::GetSafeOwner_(NULL, &hWndTop);

	// re-enable the parent window, so that focus is restored 
	// correctly when the dialog is dismissed.
	if (hWnd != hWndTop)
		EnableWindow(hWnd, TRUE);

	// set help context if possible
	DWORD* pdwContext = NULL;

	DWORD dwWndPid=0;
	GetWindowThreadProcessId(hWnd,&dwWndPid);

	if (hWnd != NULL && dwWndPid==GetCurrentProcessId() )
	{
		// use app-level context or frame level context
		LRESULT lResult = ::SendMessage(hWnd, WM_HELPPROMPTADDR, 0, 0);
		if (lResult != 0)
			pdwContext = (DWORD*)lResult;
	}
	// for backward compatibility use app context if possible
	if (pdwContext == NULL && pApp != NULL)
		pdwContext = &pApp->m_dwPromptContext;

	DWORD dwOldPromptContext = 0;
	if (pdwContext != NULL)
	{
		// save old prompt context for restoration later
		dwOldPromptContext = *pdwContext;
		if (nIDPrompt != 0)
			*pdwContext = HID_BASE_PROMPT+nIDPrompt;
	}

	// determine icon based on type specified
	if ((nType & MB_ICONMASK) == 0)
	{
		switch (nType & MB_TYPEMASK)
		{
		case MB_OK:
		case MB_OKCANCEL:
			nType |= MB_ICONEXCLAMATION;
			break;

		case MB_YESNO:
		case MB_YESNOCANCEL:
			nType |= MB_ICONQUESTION;
			break;

		case MB_ABORTRETRYIGNORE:
		case MB_RETRYCANCEL:
			// No default icon for these types, since they are rarely used.
			// The caller should specify the icon.
			break;
		}
	}

#ifdef _DEBUG
	if ((nType & MB_ICONMASK) == 0)
		TRACE(traceAppMsg, 0, "Warning: no icon specified for message box.\n");
#endif

	TCHAR szAppName[_MAX_PATH];
	szAppName[0] = '\0';
	LPCTSTR pszAppName;
	if (pApp != NULL)
		pszAppName = pApp->m_pszAppName;
	else
	{
		pszAppName = szAppName;
		DWORD dwLen = GetModuleFileName(NULL, szAppName, _MAX_PATH);
		if (dwLen == _MAX_PATH)
			szAppName[_MAX_PATH - 1] = '\0';
	}

	int nResult = MessageBox(hWnd, lpszPrompt, pszAppName, nType);

	// restore prompt context if possible
	if (pdwContext != NULL)
		*pdwContext = dwOldPromptContext;

	// re-enable windows
	if (hWndTop != NULL)
		::EnableWindow(hWndTop, TRUE);
	DoEnableModeless(TRUE);

	return nResult;
}

函数主要对于parent window以及message box的type、caption进行计算,后面调用windows api的MessageBox函数弹出提示框。

可见,AfxMessageBox是一个封装函数,它最初调用了CWnd::GetSafeOwner_, 所以它属于MFC类库中的一个函数。至于何时该调用什么函数,这就得根据函数参数、使用的SDK(链接的库)来决定了。



Q7: 用户进程都是运行在用户态下,如何获得虚拟地址的信息?

A: VirtualQuery是个获取虚拟地址信息的函数。如下例子,将获取用户进程用户空间模块的信息:

  1. int main()
  2. {
  3. MEMORY_BASIC_INFORMATION mbi;
  4. size_t ret;
  5. LPSTR p = NULL;
  6. while(1)
  7. {
  8. ret = VirtualQuery(p, &mbi, sizeof(MEMORY_BASIC_INFORMATION));
  9. if(ret == 0)
  10. {
  11. printf("query addr:%p failed...\n", p);
  12. break;
  13. }
  14. else
  15. {
  16. printf("%p AllocationProtect:%x Protect:%x size:%x\n",
  17. p, mbi.AllocationProtect, mbi.Type, mbi.RegionSize);
  18. p += mbi.RegionSize;
  19. }
  20. }
  21. while(1)
  22. ;
  23. return 0;
  24. }
int  main()
{
    MEMORY_BASIC_INFORMATION mbi;
    size_t ret;
    LPSTR p = NULL;

    while(1)
    {
	ret = VirtualQuery(p, &mbi, sizeof(MEMORY_BASIC_INFORMATION));
	if(ret == 0)
	{
	    printf("query addr:%p failed...\n", p);
	    break;
	}
	else
	{
	    printf("%p AllocationProtect:%x Protect:%x size:%x\n", 
		p, mbi.AllocationProtect, mbi.Type, mbi.RegionSize);
	    p += mbi.RegionSize;
	}

    }

    while(1)
	;
    return 0;
}

调试运行:


在vs中的模块窗口,得到如下:


可以对比下,ntdll.dll, kernel32.dll, KernelBase.dll这3个dll被加载的地址和命令行控制台中输出的地址,能够发现后者正好在前面的范围之内。



Q8: SEH异常处理和c语言的setjmp,longjump以及c++的try,catch有什么区别?

A: SEH是windows系统级别的异常处理架构,它能够处理包括浮点数异常、指令异常、堆栈溢出等系统级别的异常;而c和c++标准中的异常处理是语言级别的,像c++中throw语句才会抛出c++异常,它们无法也没有能力捕获系统级别异常。如下是使用SEH捕获堆栈异常的实例:

  1. #define PRINT_S(s) _tprintf("%s\n", (s));
  2. double fac(int n)
  3. {
  4. if(n <= 1)
  5. return 1;
  6. return n * fac(n - 1);
  7. }
  8. int main()
  9. {
  10. EXCEPTION_RECORD exceptRec;
  11. CONTEXT context;
  12. __try
  13. {
  14. //double ret = fac(10000000);
  15. //double ret = fac(100000);
  16. //double ret = fac(50000);
  17. //double ret = fac(25000);
  18. //double ret = fac(10000);
  19. double ret = fac(5000);
  20. //double ret = fac(4600); // 不会出现堆栈溢出的大概临界点
  21. }
  22. __except(exceptRec = *(GetExceptionInformation())->ExceptionRecord,
  23. context = *(GetExceptionInformation())->ContextRecord,
  24. EXCEPTION_EXECUTE_HANDLER)
  25. {
  26. switch (exceptRec.ExceptionCode)
  27. {
  28. case EXCEPTION_STACK_OVERFLOW:
  29. PRINT_S("EXCEPTION_STACK_OVERFLOW happens...")
  30. break;
  31. default:
  32. break;
  33. }
  34. }
  35. return 0;
  36. }
#define PRINT_S(s)            _tprintf("%s\n", (s)); 

double fac(int n)
{
    if(n <= 1)
	return 1;
    return n * fac(n - 1);
}

int main()
{
    EXCEPTION_RECORD exceptRec;
    CONTEXT context;

    __try
    {
	//double ret = fac(10000000);
	//double ret = fac(100000);
	//double ret = fac(50000);
	//double ret = fac(25000);
	//double ret = fac(10000);
	double ret = fac(5000);
	//double ret = fac(4600);		// 不会出现堆栈溢出的大概临界点
    }
    __except(exceptRec = *(GetExceptionInformation())->ExceptionRecord,
	context = *(GetExceptionInformation())->ContextRecord,
	EXCEPTION_EXECUTE_HANDLER)
    {
	switch (exceptRec.ExceptionCode)
	{
	case EXCEPTION_STACK_OVERFLOW:
	    PRINT_S("EXCEPTION_STACK_OVERFLOW happens...")
		break;
	default:
	    break;
	}
    }

    return 0;
}

运行结果:

如果改为c++代码,使用try, catch来捕获堆栈溢出异常:

  1. int main()
  2. {
  3. try
  4. {
  5. //double ret = fac(10000000);
  6. //double ret = fac(100000);
  7. //double ret = fac(50000);
  8. //double ret = fac(25000);
  9. //double ret = fac(10000);
  10. double ret = fac(5000);
  11. //double ret = fac(4600); // 不会出现堆栈溢出的临界点
  12. }
  13. catch(...)
  14. {
  15. PRINT_S("EXCEPTION_STACK_OVERFLOW happens...")
  16. }
  17. return 0;
  18. }
int main()
{
    try
    {
	//double ret = fac(10000000);
	//double ret = fac(100000);
	//double ret = fac(50000);
	//double ret = fac(25000);
	//double ret = fac(10000);
	double ret = fac(5000);
	//double ret = fac(4600);		// 不会出现堆栈溢出的临界点
    }
    catch(...)
    {
	PRINT_S("EXCEPTION_STACK_OVERFLOW happens...")
    }

    return 0;
}

执行后:

可以看出,它没有捕获堆栈溢出的异常。



作者:陈曦


日期:2012-9-17 18:33:23


环境:[win7 32位操作系统 Intel i3 支持64位指令 VS2012]


转载请注明出处

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值