gpt4 book ai didi

c++ - 如何在 WinCE 中捕获未处理的异常?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:47:16 27 4
gpt4 key购买 nike

在桌面 Windows 中,我可以使用 windows.h 中的 SetUnhandledExceptionFilter 函数,但它在 WinCE 中不起作用。如何在 WinCE 中捕获未处理的异常?

注意:我使用的是 C++ 而不是 .NET。

最佳答案

到目前为止,我发现的唯一方法是将应用程序中的每个线程的执行包装起来:

__try
{
// Call the thread start function here
}
__except(MyExceptionFilter(GetExceptionInformation())
{
// Handle the exception here
}

这听起来像是很多工作,但如果您编写一个像这样为您包装线程的函数,就会变得相对容易:

typedef struct {
void* startFct;
void* args;
} ThreadHookArgs;

// "params" contains an heap-allocated instance of ThreadHookArgs
// with the wrapped thread start function and its arguments.
DWORD WINAPI wrapThread(LPVOID params) {

ThreadHookArgs threadParams;
memcpy(&args, params, sizeof(ThreadHookArgs));

// Delete the parameters, now we have a copy of them
delete params;

__try {
// Execute the thread start function
return ((LPTHREAD_START_ROUTINE) threadParams.startFct) (threadParams.args);
}
__except(MyExceptionFilter(GetExceptionInformation())
{
// Handle the exception here
return EXIT_FAILURE;
}

}

然后编写自己的线程创建函数调用钩子(Hook)而不是线程启动函数:

// Drop-in replacement for CreateThread(), executes the given
// start function in a SEH exception handler
HANDLE MyCreateThread( LPSECURITY_ATTRIBUTES lpThreadAttributes,
DWORD dwStackSize,
LPTHREAD_START_ROUTINE lpStartAddress,
LPVOID lpParameter,
DWORD dwCreationFlags,
LPDWORD lpThreadId)
{
HANDLE hThread;
DWORD dwThreadId;

LPTHREAD_START_ROUTINE startFct = lpStartAddress;
LPVOID startParam = lpParameter;

// Allocate the hook function arguments on the heap.
// The function will delete them when it runs.
ThreadHookArgs* hookArgs = new ThreadHookArgs;
hookArgs->fct = lpStartAddress;
hookArgs->args = lpParameter;

// Set the start function of the created thread to
// our exception handler hook function
startFct = (LPTHREAD_START_ROUTINE) &wrapThread;
startParam = hookArgs;

// Start the hook function, which will in turn execute
// the desired thread start function
hThread = CreateThread( lpThreadAttributes,
dwStackSize,
startFct,
startParam,
dwCreationFlags,
&dwThreadId );

return hThread;
}

请注意,如果您使用的是 Windows CE 6 和更新版本,这些版本具有 vector 异常处理,这可能会更容易:

http://msdn.microsoft.com/en-us/library/ee488606%28v=winembedded.60%29.aspx

关于c++ - 如何在 WinCE 中捕获未处理的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20511702/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com