C# using C++ dll throwing exceptions
I have a C# application which dynamicly loads a C++ dll
Is it possible for the C# application to catch exceptions thrown by C++ dll?
I have a C# application which dynamicly loads a C++ dll
Is it possible for the C# application to catch exceptions thrown by C++ dll?
shade wrote:
That was not what I asked for, I wish to able to throw exceptions across lannguages.
As was said - yes, you can throw exceptions across languages as long as they are thrown from managed code.
However, If you are throwing an exception (SEH) from unmanaged code being called through p/invoke, the p/invoke layer will wrap it and throw a managed exception for you - you'll lose a lot of information, though.
In the header (.h) I have the following declaration
extern "C" SH_API void shCreateDevice(HWND hWND) throw(...);
Which is implemented as
SH_API void shCreateDevice(HWND hWND)
{
//... CODE
if(hr == D3D_OK)
{
throw CException("failed");
}
}
In the C# application i perform as follows:
public void Initialize()However even when the if is true statement in the C++ code, exception is not catched in the C# application.
Unmanaged code is not a possiblity for this case, the C++ code is a highly optimized Volume Rendering framework based upon DirectX9 and with support for DirectX10 under the Vista beta program.
Is there no way of mapping a C++ exception to C# ?
I must admit this seems a little surpricing since it puts a considerable restrain on the possiblities of interfacing C# with C++
#pragma once
#define _AFXDLL
#include <afx.h>
#include <tchar.h>
//#include "mydll.h"
void shCreateDevice(HWND hwnd) {} // Just for testing
using namespace System;
public ref class ManagedWrapper
{
public:
static void shCreateDevice(HWND hWnd) {
try {
::shCreateDevice(hWnd);
}
catch (CException& ex) {
TCHAR msg [256];
ex.GetErrorMessage(msg, 256);
throw gcnew System::Exception(gcnew String(msg));
}
}
};
Compile this code with the /clr compiler option and link your DLL's import library to resolve the native function symbols. Then use Add Reference in your C# project to reference the wrapper assembly...