Click to See Complete Forum and Search --> : No stack unwinding when ctor of unmanaged class invoked from managed code throws


gaboriux
August 10th, 2007, 01:21 PM
I am writing a managed wrapper for a native lib: a sample solution is attached. I'm using VS2005 SP1 and C++/CLI.

Three projects are involed:

NativeLib: the native library
ManagedLib: the C++/CLI classlib that is linked statically against NativeLib
StackUnwinedTestManaged: a C# console application that references and uses ManagedLib

NativeLib's cFooClass has a data member that is also a class. If the cFooClass ctor body throws, I expect stack unwinding to destroy that member, which is what happens if I use new on cFooClass from native code.

If I use new from a managed class in ManagedLib, stack unwinding does not occur: neither data members nor the ctor body's local variables are unwound.

Strangely, if I invoke a member function of an already constructed native class from managed code, and an exception is thrown, stack unwinding works normally for the function's local variables.

Is this expected behavior? Are there any project settings I'm missing that may influence this? Any comments or help is appreciated.

bzolka
August 13th, 2007, 01:07 PM
The solution is simple, though it nowhere seems to be documented. You should enable Common Language Runtime Support (/clr) for your native library if its acceptable for you. This option is accessible here: Project/Properties/Configuration properties/General page.

gaboriux
August 14th, 2007, 03:49 AM
Thank you bzolka, this helped.