Last post Apr 21, 2013 04:18 PM by Tanaka Hiero
Mar 21, 2010 06:17 PM|valerod|LINK
Hi. I'm working in a application that uses an external .Dll developed in C++ language. According the business rule, the .Dll can throws one exception if it found a error. My question is if it's possible handle or catch a exception throwed by the C++ dll?
The try/catch doesn't works. Bellow there's the code I'm using to call the C++ dll.
public extern static IntPtr LoadLibrary(string lpLibFileName);
[DllImport("kernel32", CharSet = CharSet.Ansi)]
public extern static IntPtr GetProcAddress(IntPtr hLibModule, string procName);
public extern static bool FreeLibrary(IntPtr hLibModule);
private delegate void DllMethodCallBack(string param1, string param2);
public void CallDllMethod(string param1, string param2)
IntPtr pDll = IntPtr.Zero;
// The C++ Dll is in the same path of the application. Gets the path dinamically
string path = System.Reflection.Assembly.GetExecutingAssembly().GetModules().FullyQualifiedName;
string fullPath = System.IO.Path.GetDirectoryName(path);
// Loads the C++ dll
pDll = LoadLibrary(System.IO.Path.Combine(fullPath, "DlisReader.dll"));
if (pDll == IntPtr.Zero)
throw new Exception("Load library error");
IntPtr pAddressOfFunctionToCall = GetProcAddress(pDll, "NameOfTheMethodInTheDll");
if (pAddressOfFunctionToCall == IntPtr.Zero)
throw new Exception("Library address error");
DllMethodCallBack exportData = (DllMethodCallBack)Marshal.GetDelegateForFunctionPointer(
LogError("Message -> " + ex.Message, true);
LogError("StackTrace -> " + ex.StackTrace, true);
LogError("Source -> " + ex.Source, true);
bool result = FreeLibrary(pDll);
throw new Exception("Free library error");
Thanks in advance.
Apr 06, 2010 05:10 PM|timallard|LINK
My reaction is that you have a System.Exception and it's bubbling up ... maybe wrap that dll in a class and handle it's exceptions that way instead of using it directly.
Apr 21, 2013 04:18 PM|Tanaka Hiero|LINK
It is a heavy platform implementation detail. In general, the exception plumbing is somewhat likely to be able to unwind the stack through C function activation frames. Necessary because the CRT is often written in C. However, the C code is pretty unlikely
to be happy about it, state got mutated that cannot be restored.
Just in case this is Windows, the C code does have a shot at it. C++ exceptions are piggy-backed onto the generic exception support built into Windows, called Structured Exception Handling (SEH). You use the __try and __except keywords to call an exception
filter that can restore the C code state. Obviously this is not portable.
Never ask an implementation detail question without mentioning the implementation details, please.