3

I created a C++ dll and i want to use that dll in C#. i created three functions in dll

Initializ(),Start(),Release()

in the initialize function i am opening a log file

static __declspec(dllexport) initialize()
{
    try
    {
       logfile lg("log.txt");
    }
    catch(exception e)
    {
    throw e.what();
    }
}

after that i am calling this initialize function in C#

[DllImport("LgDll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void Initialize();
private void button1_Click(object sender, EventArgs e)
{
    try
    {
        Initialize()
        catch (SEHException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

this is my c# application where i am calling this function. now i want that if log file is not opening in dll than it throw error outside the dll and the C# application has to decide weather to continue the application or abort the application or ignore the error. please some body help me with sample C++ code. so that the C++ dll send the exception outside the dll and wait for C# app response.

Rohit Prakash
  • 1,975
  • 1
  • 14
  • 24
Engr
  • 161
  • 1
  • 5
  • 13

1 Answers1

0

SEHException is used for capturing Windows Structured Exceptions, and not C++ exceptions. Structured exceptions (__try/__except) are implemented by the OS and are stable within a Windows process space. C++ exceptions (try/catch)are implemented by the compiler and are only guaranteed to be stable within one compilation unit (usually a single DLL or exe).

The kinds of things that raise SEHExceptions are usually access violation, division by zero, out of memory, or other things that cause a process crash. You probably shouldn't be generating these on your own, but if you really want then look into the RaiseException function.

A better way of indicating a non-crash error state in the DLL would be to have your Initialize, Start, and Release functions return an error code. The caller can then check this code and re-throw if needed.

See also:

Difference between a C++ exception and Structured Exception

SEHException not caught by Try/Catch

Community
  • 1
  • 1
Ryan Bemrose
  • 9,018
  • 1
  • 41
  • 54