Bonjour,

J'ai une solution pour récupérer l'exception .NET dans un __try/__except (donc handler d'exception non managé).

Il s'agit de relancer (dans un try/catch .NET) l'exception avec un RaiseException.

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
 
#include <Windows.h>
#define DOT_NET_EXCEPTION_CODE 0xE0434352
 
void RetrieveDotNetExceptionInfo(_EXCEPTION_RECORD * ExceptionRecord) {
	try {
		RaiseException(ExceptionRecord->ExceptionCode,
					   ExceptionRecord->ExceptionFlags,
					   ExceptionRecord->NumberParameters,
					   ExceptionRecord->ExceptionInformation);
	} catch(System::Exception ^E) {
		System::Console::WriteLine(E->ToString());
	}
}
 
#define KindOfDotNetException 3
void DoSomeManagedThrow() {
	switch (KindOfDotNetException) {
		case 1:
			{ throw gcnew System::Exception("une exception .NET"); }
		case 2:
			{ System::Int32 ^i = 32;
			  System::String^ s = (System::String^)i; }
		case 3:
			{ System::Int32 ^i = nullptr;
			  i->GetType(); }
		case 4: // this one doesn't work --> infinte loop (it's a bug of VS2010 compiler ?)
			{ System::Int32 ^i = nullptr;
			  i->ToString(); }
	}
}
 
#pragma unmanaged 
 
int HandleException(void *ptr) {
	_EXCEPTION_RECORD * ExceptionRecord = ((_EXCEPTION_POINTERS*)ptr)->ExceptionRecord;
	switch (ExceptionRecord->ExceptionCode) {
		case DOT_NET_EXCEPTION_CODE:
			RetrieveDotNetExceptionInfo(ExceptionRecord);
			return EXCEPTION_EXECUTE_HANDLER;
		default:
			/***/ ;
	}
	return EXCEPTION_CONTINUE_SEARCH;
}
 
void UnmanagedTry() {
	__try {
		DoSomeManagedThrow();
	} __except(HandleException(_exception_info())) {
	}
}
#pragma managed
 
int main(array<System::String ^> ^args)
{
	/* to compare with normal .NET exception catch :
        try {
		DoSomeManagedThrow();
	} catch(System::Exception ^E) {
		System::Console::WriteLine(E->ToString());
	}
	System::Console::WriteLine(""); */
	UnmanagedTry();
	system("pause");
    return 0;
}
Si quelqu'un connait une autre solution pour ce problème ça m'intéresserait de la connaître !