I'm trying to throw exceptions out of an unmanaged C++ static lib and catch them in a managed C++ dll. For some reason, I'm failing miserably. Here's the code:
Code:
//In MyException.h
#ifndef MYEXCEPTION_H_NKJSFNE_09829232
#define MYEXCEPTION_H_NKJSFNE_09829232
#include <cwchar>
class MYException
{
public:
MYException(wchar_t* pszErrorMsg) : m_pszErrorMsg(pszErrorMsg) {}
wchar_t* Report();
virtual ~MYException() {}
private:
wchar_t* m_pszErrorMsg;
};
void ThrowException();
#endif
Code:
//In MyException.cpp
#include "MYException.h"
void ThrowException()
{
throw new MYException(L"C++ exception");
}
wchar_t* MYException::Report()
{
return m_pszErrorMsg;
}
Code:
//In CppManaged.h
#pragma once
#include "MYException.h"
using namespace System;
namespace CppManaged
{
public __gc class ExceptionCatch
{
public:
void Go();
};
}
Code:
//In CppManaged.cpp
#include "CppManaged.h"
using namespace CppManaged;
void ExceptionCatch::Go()
{
try
{
ThrowException();
}
catch (MYException* pExcep)
{
String* a = new String(pExcep->Report());
delete pExcep;
throw new Exception(a);
}
catch (Object* pObj)
{
throw new Exception(pObj->ToString());
}
}
Code:
//In Driver.cs
using System;
using System.IO;
using CppManaged;
namespace ConsoleException
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
ExceptionCatch a = new ExceptionCatch();
try
{
a.Go();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
When I write out the caught exception, I get the following:
Code:
System.NullReferenceException: Object reference not set to an instance of an object.
at ThrowException()
at CppManaged.ExceptionCatch.Go() in cppmanaged.cpp:line 10
Obviously, that's not my exception. Can anyone tell me what's going on?