简体   繁体   中英

Pass ptr to lpArguments in Win32 RaiseException API?

I call RaiseException in my code if I need to stop execution. This puts an entry into the Event Viewer Application Log, as expected. I would like the Event Viewer to contain data.

According to documentation for RaiseException , the lpArguments parameter can do this, but it takes a ULONG_PTR parameter.

Here is my code: RaiseException(58585,0,0,NULL);

Is there an example someone can show of how to pass a pointer to a string for the last parameter in the function RaiseException ?

You can pass everything to lpArguments in Win32 RaiseException API. You can refer to the following code.

#include <windows.h>
#include <stdio.h>
#include <strsafe.h>

struct MySEHExceptionStruct
{
    DWORD Index;
};

#define EXCEPTION_CUSTOM_1 0x1

void TestRaiseException()
{
    // First allocate space for a MySEHExceptionStruct instance.
    MySEHExceptionStruct* pMySEHExceptionStruct = (MySEHExceptionStruct*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(MySEHExceptionStruct));
    if (pMySEHExceptionStruct)
    {
        pMySEHExceptionStruct->Index = 0x999;
    }

    LPVOID lpszMessage2 = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 255 * sizeof(TCHAR));
    if (lpszMessage2)
    {
        StringCchPrintf((LPTSTR)lpszMessage2, LocalSize(lpszMessage2) / sizeof(TCHAR), TEXT("Exception Message %d."), 2);
    }

    ULONG_PTR lpArguments[2]{};
    if (lpArguments)
    {
        lpArguments[0] = (ULONG_PTR)pMySEHExceptionStruct;
        lpArguments[1] = (ULONG_PTR)lpszMessage2;
    }

    RaiseException(EXCEPTION_CUSTOM_1, 0, 2, lpArguments);
}

DWORD g_nNumberOfArguments;
ULONG_PTR* g_lpArguments;

DWORD FilterFunction(LPEXCEPTION_POINTERS info)
{
    printf("1 ");                     // printed first
    if (info->ExceptionRecord->ExceptionCode == EXCEPTION_CUSTOM_1)
    {
        g_nNumberOfArguments = info->ExceptionRecord->NumberParameters;
        //not sure pointer copy or value copy
        g_lpArguments = info->ExceptionRecord->ExceptionInformation;
        return EXCEPTION_EXECUTE_HANDLER;
    }
    else
    {
        return EXCEPTION_CONTINUE_SEARCH;
    }
}

BOOL CallTestRaiseException()
{
    __try
    {
        TestRaiseException();
    }
    __except(FilterFunction(GetExceptionInformation()))
    {
        if (g_nNumberOfArguments > 0)
        {
            MySEHExceptionStruct* pMySEHExceptionStruct = (MySEHExceptionStruct*)g_lpArguments[0];
            TCHAR* lpszMessage2 = (TCHAR*)g_lpArguments[1];

            HeapFree(GetProcessHeap(), HEAP_ZERO_MEMORY, pMySEHExceptionStruct);
            HeapFree(GetProcessHeap(), HEAP_ZERO_MEMORY, lpszMessage2);
        }
        return FALSE;
    }
    return TRUE;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM