Microsoft KB Archive/841888

= How to obtain unmanaged stack information from a managed block of code in Microsoft Visual Studio .NET =

Article ID: 841888

Article Last Modified on 5/18/2007

-

APPLIES TO


 * Microsoft Common Language Runtime (included with the .NET Framework) 1.0

-





INTRODUCTION
When you work in Microsoft Visual Studio .NET with managed code, you may want to step through the stack of unmanaged code from a try catch block of managed code. This article describes how to step through a stack of unmanaged code from a try catch block of managed code.



MORE INFORMATION
There is no intrinsic way to step through a stack of unmanaged code from a block of managed code. If you are working with managed code, and you want to step through the stack of unmanaged code, you must use Platform Invocation Services (PInvoke) to call the GetExceptionInformation function and the StackWalk64 function of the Win32 API.

If you receive an exception from your unmanaged code, you must leave the managed code block through your Filter function that is used for exception handling. The Win32 API GetExceptionInformation function is valid only in the Filter function. You can only step through the stack in the Filter function. When execution reaches the Handler function, the exception is complete, and any stack information that executes before the exception is now invalid.

Programmers of managed languages frequently hide the Filter function and instead use multiple Catch clauses. To obtain valid stack information, you must use the Filter function. If you step through the unmanaged stack outside the Filter function, you will receive unpredictable and frequently hazardous results.

The following code samples show you where to step through a stack of unmanaged code from a block of managed code: //C++ code--// __try Code; __except(Filter) Handler;

int Filter {   // Inside the Filter statement. PInvoke to Win32 DbgHelp APIs here to stackwalk. return 1; // returning -1 or 0 will cause Filter to fail, Handler is not executed and the next outer exception block will be used. } '//--VB .NET code---// Module Module1

Sub Main Try Throw New System.NullReferenceException Catch When Filter System.Console.WriteLine(&quot;Caught exception&quot;) End Try End Sub

Function Filter as boolean ' Inside Filter. PInvoke to Win32 DbgHelp APIs here to stackwalk. return True     ' If you return False from Filter, Catch does not execute and the next outer Try/Catch block will be used. End Function

End Module You cannot create a Filter function with the C# language.

