Stack is not unwinded when called from C#
I have a DLL developed using C++. In it I define a class that has a
destructor. I also define a function that creates a class object from
the mentioned class on the stack. This function may throw an
exception, and when it does the stack is unwinded and the destructor
is called for the class object. However when calling the function from
another C# application the destructor is never called!
Here's a sample that explains the situation:
[code]
//----------- The C++ Program
#include <iostream>
class Logger
{
public:
Logger() { std::cout << "Constructor called" <<
std::endl;};
~Logger() { std::cout << "Destructor called" <<
std::endl;};
};
void Throw()
{
Logger log; // Should be destructed upon leaving this
block
throw std::exception();
}
//---------- The C# program
[DllImport("ThrowingDLL.dll", EntryPoint = "Throw")]
public static extern void Throw();
static void Main()
{
try
{
Throw();
}
catch { Console.WriteLine("Exception caught"); }
}
/*----- This produces the following Output:
Constructor called
Exception caught
*/
[/code]
Note that if my Throw function was like this:
[code]
void Throw()
{
try{
Logger log; // Should be destructed upon
leaving this block
throw std::exception();
}
catch (const std::exception& e) {
throw e; // Rethrow exception
}
}
[/code]
Everything works as expected and the output becomes:
Constructor called
Destructor called
Exception caught
Is this a bug or is it expected behavior?
I use VS 2005. Can you confirm if VS 2008 have the same behavior?
Abdo Haji-Ali
Programmer
In|Framez