Solved

How to force CLR not to handle Exceptions from unmanaged code ?

Posted on 2008-10-27
8
1,295 Views
Last Modified: 2013-12-17
Hi experts...
I have managed code in C# calling unmanaged code from a DLL written in C++.
Every time an Exception is thrown by unmanaged code, this exception is handled by C# directly.
How to force to handle the exception by the DLL itself, instead of C# ?

example attached below.
   
//C# code

[DllImport("some.dll")]

    public static extern int A();

static int Main()

{

    try {

        A();

    } catch {

        // handle exception by managed code

    }

}
 

// C++ code

extern "C" __declspec(dllexport) int A();

int B(void);
 

int A()

{

    try {

        B();

    } catch (...) {

        // handle exception by unamanged code

        // how to handle the exeption here ???

    }

}
 

int B()

{

    // throw some exception

    throw;

}

Open in new window

0
Comment
Question by:darkriser
  • 5
  • 3
8 Comments
 
LVL 23

Expert Comment

by:Jens Fiederer
ID: 22814686
Are you able to rewrite the DLL?

If so, make sure you catch the error.

If not, you could avoid calling the DLL from C#, but only from ANOTHER unmanaged DLL that calls it, catching all errors.

Obviously, you aren't going to change the DLL itself without changing the DLL.
0
 
LVL 1

Author Comment

by:darkriser
ID: 22819880
Yes, of course I can rewrite the DLL. But how to achieve my requirements?

The problem is, that as soon as the C# code detects some exception inside my unmanaged DLL, it immediately skips the catch block inside the DLL and starts the C# catch block. Therefore I'm unable to handle exceptions inside my unmanaged DLL.
0
 
LVL 23

Expert Comment

by:Jens Fiederer
ID: 22821385
Maybe you should be throwing SOMETHING instead of a naked throw?

When I use your code as written, I crash with "application has asked the runtime to terminate it in an unusual way" .

But when I throw (for example) an int,  I get a usable function.

See snippet.
C++
 

extern "C" __declspec(dllexport) int A();

int B(int);

 

int A(int parm)

{

    try {

		if (parm == 1) 

		{

			return B(parm);

		}

    } catch (int exc) {

        return exc;

	} catch (...) {

		return 100;

	}
 

	return parm*2;

}

 

int B(int parm)

{

    // throw some exception

    throw parm*3;

}
 

# C# test program

namespace usemanaged

{

    

    class Program

    {

        [DllImport("unmanageddll.dll", EntryPoint = "A",

        ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)]

        static extern int A(int parm);
 

        static void Main(string[] args)

        {

            while (true)

            {

                int parm = int.Parse(Console.ReadLine());
 

                int z = A(parm);

                Console.WriteLine(z.ToString());

            }

        }

    }

}

Open in new window

0
 
LVL 23

Expert Comment

by:Jens Fiederer
ID: 22821424
'a naked call to "throw;" will terminate the program if not invoked during the execution of a catch-handler.'

according to
http://www.velocityreviews.com/forums/t282888-abort-instead-of-throwing-exceptions.html
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 1

Author Comment

by:darkriser
ID: 22822044
That's a good point.
But my problem is a little bit different (haven't mentioned this in my orig post, my fault).
What if unmanaged DLL fails in accessing dynamically allocated memory (trying to access element outside array's boundary)? Then I receive following error from C# directly and catch(...) block inside the DLL is ignored. How to catch this type of error within the DLL?

An unhandled exception of type 'System.AccessViolationException' occurred in Test.exe

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
0
 
LVL 23

Accepted Solution

by:
Jens Fiederer earned 250 total points
ID: 22822601
If you are using Visual Studio to compile your C++ dll, there is a project option under C/C++ code generation called "Enable C++ Exceptions".

When I had it set to "Yes (/EHsc)" my C++ did not catch the exception.
But when I had it set to "Yes With SEH Exceptions (/EHa)" my C++ DID catch the exception in the unmanaged code.
0
 
LVL 1

Author Closing Comment

by:darkriser
ID: 31510359
I have missed this option because it is written in very small font :-)
No, seriously, this is what I've been looking for.
Thanks many times.
0
 
LVL 23

Expert Comment

by:Jens Fiederer
ID: 22823594
Glad to help, that was a fun one.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Loop not working 29 47
max float value 3 25
Angular - break the dataset in chunks? 7 39
Visual Studio 2015 Source Code Control 10 32
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

912 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now