I'm creating a C++ DLL to be used in C#. This DLL throws exceptions whenever anything is wrong and the idea is to handle these in the C# code.
I created a new exception class in C++ inheriting from std::runtime_error
because I not only need the what
but also a numeric ID:
class insight_exception: public std::runtime_error
{
public:
explicit insight_exception(const int id, const std::string message):
std::runtime_error(message), id{id}
{}
virtual ~insight_exception() noexcept {}
const int id;
};
Whenever something goes wrong in the C++ code I do this:
throw insight_exception(103, "size Pointer is NULL");
I have a little example in C# to "exercise" the DLL, just to test it before sending it to our C# developer, and when I execute the little C# program I can verify that the DLL is throwing the exceptions because I'm getting this:
terminate called after throwing an instance of 'insight_exception'
My problem is that I don't know any C# and I don't really know to "import" the insight_exception
class into C# so I can catch it.
Solutions like this post don't help because they assume you can use the class by using a function like this:
insight_exception* create_insight_exception()
{
return new insight_exception();
}
And I can't do that because I need something like this in C#
try
{
}
catch (insight_exception e)
{
}
So I can't create the class like:
IntPtr insight_exception = create_insight_exception();
One important thing to know is that I'm creating the DLL on Linux by cross-compiling using MinGW, so I can't do #include <Windows.h>
or any other windows-related includes or imports when creating the DLL. I don't really use Windows but only for my little test C# code.
EDIT:
Thanks to a comment, I looked into the following questions:
C# not catching unhandled exceptions from unmanaged C++ dll
This one looks promising but the problem is that the answer suggest a compilation done in Windows. I tried to add the /EHa
compilation flag equivalent in GCC (-funwind-tables) but that doesn't help. I still can't catch the exception using catch (SEHException ex)
nor catch (Exception ex)
in the C# code.
Can you catch a native exception in C# code?
Suggests using Win32Exception
but that doesn't work either. I can't catch the exception with catch (Win32Exception ex)
in the C# code.