Background: I developed an Activex control in .NET, but found it was causing stability issues in various applications that used it. I managed to find a series of steps, from sample applications, similar unstabilities outlined below.
I have a sample Activex control that I've downloaded from the Dev-Center website called 'CSActivex' (http://code.msdn.microsoft.com/windowsdesktop/CSActiveX-b86194f8)
It was fairly easy to build, I just loaded the project up in VS2010 Express (C#) and it compiled into a .dll
I then created a sample MFC application from VS2008 C++ to model a legacy applications (it does not use any .NET). The target is the simple dialog based GUI that has an About box.
I registered the csactivex.dll with regasm and just copied the dll to the VS IDE folder, so I can insert the Activex control at design time, and then to the Debug folder, so it can be found during runtime.
At design time, I insert the CSActivex control onto the About dialog box, it appears with no surprises. After building and copying the dll to the Debug folder and run a debug session, if I continually navigate to the about box, click in various places on the control, close the about dialog and repeat a few times, I start to see messages in the output log about access violations, and it starts to look like this:
'CSActivexMFC.exe': Loaded 'C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\System.Windows.Forms\63406259e94d5c0ff5b79401dfe113ce\System.Windows.Forms.ni.dll'
'CSActivexMFC.exe': Loaded 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorjit.dll'
'CSActivexMFC.exe': Loaded 'C:\WINDOWS\WinSxS\x86_Microsoft.Windows.GdiPlus_6595b64144ccf1df_1.0.2600.5581_x-ww_dfbc4fc4\GdiPlus.dll'
'CSActivexMFC.exe': Loaded 'C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\Accessibility\11eb4f6606ba01e5128805759121ea6c\Accessibility.ni.dll'
First-chance exception at 0x00000000 in CSActivexMFC.exe: 0xC0000005: Access violation reading location 0x00000000.
First-chance exception at 0x00000000 in CSActivexMFC.exe: 0xC0000005: Access violation reading location 0x00000000.
First-chance exception at 0x79f4c2f7 in CSActivexMFC.exe: 0xC0000005: Access violation reading location 0x0000000b.
First-chance exception at 0x79f4c2f7 in CSActivexMFC.exe: 0xC0000005: Access violation reading location 0x0000000b.
While it does not crash in the debugger, I can't help but think this in not good, and I have a feeling that it may be related to the instability of other .NET Activex controls. If I can figure out a way to solve this issue, the same resolution may help the original control.
I tried breaking on the exception, but it appears to happen in a few different places. one stack trace when I closed the applications is below:
mscorwks.dll!79f4c2f7() [Frames below may be incorrect and/or
missing, no symbols loaded for mscorwks.dll]
mscorwks.dll!79f4c370() mscorwks.dll!79faaa91()
mscorwks.dll!79faa858() mscorwks.dll!79faa9ad()
mscorwks.dll!79faa9d9() mscorwks.dll!7a079480()
mscorwks.dll!7a0798e8() mscorwks.dll!7a043f25()
ole32.dll!77525834() rpcrt4.dll!77e799f4()
rpcrt4.dll!77ef421a() ntdll.dll!7c915239()
ntdll.dll!7c91542b() ntdll.dll!7c91534a()
ntdll.dll!7c915239() ntdll.dll!7c91542b()
ntdll.dll!7c91534a() ntdll.dll!7c915f75()
ntdll.dll!7c9155ed() ntdll.dll!7c915ce9()
ntdll.dll!7c96f07c() ole32.dll!77600c15()
ole32.dll!77600bbf() ole32.dll!7752ad31()
ole32.dll!7752ac56() ole32.dll!7752b771()
ole32.dll!77600e1f() ole32.dll!7752b7ab()
ole32.dll!7752b5e1() ole32.dll!7752b54e()
user32.dll!7e418734() ole32.dll!7752b54e()
ole32.dll!7752b54e() ole32.dll!7752b54e()
ole32.dll!7752b54e() ole32.dll!7752f2d0()
ole32.dll!7752f23e() ole32.dll!77557237()
mscorwks.dll!79f9e14d() mscorwks.dll!79f9e0b4()
mscorwks.dll!79f9e018() mscorwks.dll!79f4c879()
mscorwks.dll!79f3bb76() mscoreei.dll!603cc966()
mscoreei.dll!603d1f25() mscoree.dll!790186ad()
msvcr90d.dll!_crtCorExitProcess(int status=2) Line 716 C msvcr90d.dll!_crtExitProcess(int status=2) Line 722 + 0x9 bytes C
msvcr90d.dll!doexit(int code=2, int quick=0, int retcaller=0) Line
644 + 0x9 bytes C msvcr90d.dll!exit(int code=2) Line 412 + 0xd
bytes C CSActivexMFC.exe!__tmainCRTStartup() Line 595 C
CSActivexMFC.exe!wWinMainCRTStartup() Line 399 C
kernel32.dll!7c817077()
I was hoping someone may have run into this before, I'm running into this on mulitple machines (home and at work) and at least have it narrowed down to either a problem with CSActivex not doing something it should, or something in MFC.
so my question is how to get these samples working without the access violations?
Edit:
Just opening the about window and closing it repeatedly eventually results in a crash in the debugger (unhandled exception) with a stack trace below, to me it looks like an object that was destructed is being destroyed again?
First-chance exception at 0x00400003 in CSActivexMFC.exe: 0xC0000005: Access violation writing location 0x00000000.
First-chance exception at 0x00400003 in CSActivexMFC.exe: 0xC0000005: Access violation writing location 0x00000000.
First-chance exception at 0x003a005c in CSActivexMFC.exe: 0xC0000096: Privileged instruction.
First-chance exception at 0x00460020 in CSActivexMFC.exe: 0xC0000005: Access violation reading location 0x00460020.
First-chance exception at 0x78b6ba1d (mfc90ud.dll) in CSActivexMFC.exe: 0xC0000005: Access violation writing location 0x00000018.
Unhandled exception at 0x78b6ba1d (mfc90ud.dll) in CSActivexMFC.exe: 0xC0000005: Access violation writing location 0x00000018.
mfc90ud.dll!CDataSourceControl::~CDataSourceControl() Line 2431 + 0x2d bytes C++
mfc90ud.dll!CDataSourceControl::`scalar deleting destructor'() + 0x11 bytes C++
mfc90ud.dll!COleControlSite::~COleControlSite() Line 77 + 0x22 bytes C++
mfc90ud.dll!COleControlSite::`scalar deleting destructor'() + 0x11 bytes C++
mfc90ud.dll!COleControlSiteOrWnd::~COleControlSiteOrWnd() Line 161 + 0x24 bytes C++
mfc90ud.dll!COleControlSiteOrWnd::`scalar deleting destructor'() + 0x11 bytes C++
mfc90ud.dll!COleControlContainer::~COleControlContainer() Line 199 + 0x1c bytes C++
mfc90ud.dll!COleControlContainer::`scalar deleting destructor'() + 0x11 bytes C++
mfc90ud.dll!CWnd::OnDestroy() Line 786 + 0x24 bytes C++
mfc90ud.dll!CWnd::OnWndMsg(unsigned int message=2, unsigned int wParam=0, long lParam=0, long * pResult=0x0012f510) Line 2042 C++
mfc90ud.dll!CWnd::WindowProc(unsigned int message=2, unsigned int wParam=0, long lParam=0) Line 1755 + 0x20 bytes C++
mfc90ud.dll!AfxCallWndProc(CWnd * pWnd=0x0012f88c, HWND__ * hWnd=0x002c04fc, unsigned int nMsg=2, unsigned int wParam=0, long lParam=0) Line 240 + 0x1c bytes C++
mfc90ud.dll!AfxWndProc(HWND__ * hWnd=0x002c04fc, unsigned int nMsg=2, unsigned int wParam=0, long lParam=0) Line 403 C++
mfc90ud.dll!AfxWndProcBase(HWND__ * hWnd=0x002c04fc, unsigned int nMsg=2, unsigned int wParam=0, long lParam=0) Line 441 + 0x15 bytes C++
user32.dll!7e418734()
[Frames below may be incorrect and/or missing, no symbols loaded for user32.dll]
user32.dll!7e418816()
mfc90ud.dll!CThreadSlotData::GetThreadValue(int nSlot=6623744) Line 268 C++
user32.dll!7e428eec()
ntdll.dll!7c90e473()
user32.dll!7e42b1a8()
mfc90ud.dll!CWnd::DestroyWindow() Line 1007 + 0xd bytes C++
90909090()
Take a look at this MSDN Blog by David Kline on What is a First Chance Exception.
From Blog
Does a first chance exception mean there is a problem in my code?
First chance exception messages most often do not mean there is a problem in the code. For applications / components which handle exceptions gracefully, first chance exception messages let the developer know that an exceptional situation was encountered and was handled.
For code without exception handling, the debugger will receive a second chance exception notification and will stop with a unhandled exception.
And by looking at another MSDN Blog by David Kline it will tell you how to Stop on a First Chance Exception to see what caused it.
And this MSDN Forum Posting
Related
I'm looking into a mini-dump file where the main thread (c++) utilized CLR to launch a managed (C#.NET) window, an exception was thrown in the managed portion, and crashed the application. I've been searching around looking at techniques to examine an exception details for clues, however they're mainly for one or the other (an entirely unmanaged stack & thread or an entirely managed stack & thread).
The portion of the managed callstack is below, where I can see an exception was raised inside the .NET portion, but I'm not really sure of a method to digging into viewing the details of what was raised. I'm still fairly new at digging through a .dmp file, so any guidance is greatly appreciated.
001ddb04 68b92a42 KERNELBASE!RaiseException+0x58
001ddba8 68c655ef clr!RaiseTheExceptionInternalOnly+0x276
001ddbd8 68c6de52 clr!UnwindAndContinueRethrowHelperAfterCatch+0x83
001ddc6c 627528df clr!CEEInfo::resolveToken+0x59b
001ddc7c 62778872 clrjit!Compiler::impResolveToken+0x3a
001de3ac 62751d53 clrjit!Compiler::impImportBlockCode+0x29b3
001de42c 62751f48 clrjit!Compiler::impImportBlock+0x5f
001de444 62753405 clrjit!Compiler::impImport+0x235
001de464 62753635 clrjit!Compiler::compCompile+0x63
001de4a0 62753823 clrjit!Compiler::compCompileHelper+0x2fa
001de518 627536f6 clrjit!Compiler::compCompile+0x213
001de608 6275385f clrjit!jitNativeCode+0x1e3
001de62c 68a74710 clrjit!CILJit::compileMethod+0x25
001de67c 68a747a9 clr!invokeCompileMethodHelper+0x41
001de6bc 68a747eb clr!invokeCompileMethod+0x31
001de720 68a73684 clr!CallCompileMethodWithSEHWrapper+0x2a
001deab8 68a73920 clr!UnsafeJitFunction+0x3ca
001deb94 68a81e5e clr!MethodDesc::MakeJitWorker+0x36b
001dec08 68a550b6 clr!MethodDesc::DoPrestub+0x59d
001dec70 68a44279 clr!PreStubWorker+0xed
001deca0 16c5185a clr!ThePreStub+0x16
001deda4 5ae8f887 0x16c5185a
001dedc0 5ae20c9c MYDLL!CLoader::InvokeCSharpControl
0x16c5185a is an address in memory where the .NET code has been compiled by the JIT compiler. Due to the just-in-time compilation, there's no symbol like in C++ and you need different tools (extensions for WinDbg).
First, check if it's a .NET exception with .exr -1. Except for a few exceptions, the code should be 0xE0434F4D (.COM in ASCII characters).
If that's the case, load the SOS extension to analyze the .NET details: .loadby sos clr. Next, run the command !PrintException (!pe in short) to get details about the exception and !ClrStack (casing is not relevant) to get details about the .NET call stack.
There may be more details available if you have a good crash dump for .NET.
A couple of years ago I inherited a C# app that uses COM objects defined in an unmanaged C++ DLL. I've been successfully tweaking the object interfaces ever since, but following a (possibly irrelevant) VS2012 upgrade, function signature additions and changes are suddenly being punished by random exceptions such as ExecutionEngineException and SEHException.
My understanding was that the app uses registration-free COM. There's no DLLRegisterServer implementation, and I see no mention of the interface guids in the registry, just one in C#...
[ComImport,
Guid("C2427CB1-D6AE-49e8-B266-114F981C3353"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
SuppressUnmanagedCodeSecurity()]
public interface IDC
{
and one in a C++ header.
interface __declspec(uuid("C2427CB1-D6AE-49e8-B266-114F981C3353"))
IDC : IUnknown
{
To be sure though, I decided to swap a new guid into these two places, and discovered that it stopped C# from recognizing the class at all:
System.InvalidCastException
Unable to cast COM object of type 'System.__ComObject' to interface type 'Apx.IDC'.
This operation failed because the QueryInterface call on the COM component for the
interface with IID '{the new guid}' failed due to the following error:
No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
(The above error is apparently often caused by mixing appartment states, but swapping a guid doesn't cause that). So I deduce there must be additional relevant detail somewhere that's conflicting with my changes. But where might that somewhere be? Thanks for reading...
Edit:
An example exception is...
First-chance exception at 0x000007feec748be4 (clr.dll) in Apex.exe: 0xC0000005:
Access violation reading location 0xffffffffffffffff.
The Common Language Runtime cannot stop at this exception. Common causes include:
incorrect COM interop marshalling, and memory corruption. To investigate further,
using native-only debugging.
An unhandled exception of type 'System.ExecutionEngineException' occurred in Apex.exe
for
[PreserveSig] [return: MarshalAs(UnmanagedType.I1)]
bool LoadDisplayList(IntPtr fileHandle, IntPtr pDisplayList,
UInt16 version, IntPtr pComparison);
and
virtual bool __stdcall LoadDisplayList(HANDLE fileHandle, class CDisplayList * pDisplayList,
WORD version, CDisplayList * pComparison) = 0;
with a stack trace ending
[Native to Managed Transition]
Apex.Graphics64.dll!CDisplayList::LoadRenderRecs(void * f=0x000000000000056c, CDisplayList * pComparison=0x0000000023ad2cf0) Line 1772 C++
Apex.Graphics64.dll!CDisplayList::Load(void * f=0x000000000000056c, unsigned short version=0x0002, CDisplayList * pComparison=0x0000000023ad2cf0) Line 1845 + 0x26 bytes C++
Apex.Graphics64.dll!CBaseDC::LoadDisplayList(void * f=0x000000000000056c, CDisplayList * pList=0x0000000023ad2cf0, unsigned short version=0x0002, CDisplayList * pComparison=0x0000000023ad2cf0) Line 1896 + 0x33 bytes C++
[Managed to Native Transition]
Apex.exe!Apex.DDC.LoadDisplayList(System.IO.FileStream file = {System.IO.FileStream}, Apex.DisplayList displayList = {Apex.DisplayList}, ushort version = 0x0002, Apex.DisplayList comparison = null) Line 1124 + 0xaf bytes C#
Apex.exe!Apex.DisplayList.Load(System.IO.FileStream f = {System.IO.FileStream}, ushort loadVersion = 0x0002, Apex.INode stubsRoot = {Apex.ViewPort3D}, Apex.DisplayList comparison = null) Line 166 + 0x53 bytes C#
The exact crash point varies somewhat - here it actually managed to get inside LoadDisplayList(), which is better than usual. As the crash suggests heap damage, I've tried stripping the function's signature down to a parameterless void return, reduced its contents to a trace, and called it right after the object's creation - still to get a crash. The same function doesn't crash if I move it to the top of the definitions, in which case some other interface function crashes out instead, leading me to think it's more likely to be a COM problem than algorithm-level memory corruption.
I think I've fixed the problem. Once I was able to step into the DLL a little, a popup saying that the source didn't match the executable led me to investigate another longstanding but previously unproblematic quirk, that the DLL's Linker / General / Output File wasn't inside the project's General / Output Directory (warning MSB8012). After cleaning up this anomaly I was able change the guid successfully, so it seems VS2012 uses these settings slightly differently to older versions. The moral...don't let warnings hang around.
I have a handle leak in a C# program. I'm trying to diagnose it using WinDbg using !htrace, roughly as presented in this answer, but when I run !htrace -diff in WinDbg I'm presented with stack traces that don't show the names of my C# functions (or even my .net assembly).
I created a small test program to illustrate my difficulty. This program does nothing except "leak" handles.
class Program
{
static List<Semaphore> handles = new List<Semaphore>();
static void Main(string[] args)
{
while (true)
{
Fun1();
Thread.Sleep(100);
}
}
static void Fun1()
{
handles.Add(new Semaphore(0, 10));
}
}
I compiled the assembly, and then in WinDbg I go "File" -> "Open Executable" and select my program (D:\Projects\Sandpit\bin\Debug\Sandpit.exe). I continue program execution, break it, and run "!htrace -enable", then continue for a bit longer, and then break and run "!htrace -diff". This is what I get:
0:004> !htrace -enable
Handle tracing enabled.
Handle tracing information snapshot successfully taken.
0:004> g
(1bd4.1c80): Break instruction exception - code 80000003 (first chance)
eax=7ffda000 ebx=00000000 ecx=00000000 edx=77b2f17d esi=00000000 edi=00000000
eip=77ac410c esp=0403fc20 ebp=0403fc4c iopl=0 nv up ei pl zr na pe nc
cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000246
ntdll!DbgBreakPoint:
77ac410c cc int 3
0:004> !htrace -diff
Handle tracing information snapshot successfully taken.
0xd new stack traces since the previous snapshot.
Ignoring handles that were already closed...
Outstanding handles opened since the previous snapshot:
--------------------------------------
Handle = 0x00000250 - OPEN
Thread ID = 0x00001b58, Process ID = 0x00001bd4
0x77ad5704: ntdll!ZwCreateSemaphore+0x0000000c
0x75dcdcf9: KERNELBASE!CreateSemaphoreExW+0x0000005e
0x75f5e359: KERNEL32!CreateSemaphoreW+0x0000001d
*** WARNING: Unable to verify checksum for C:\Windows\assembly\NativeImages_v4.0.30319_32\System\13c079cdc1f4f4cb2f8f1b66c8642faa\System.ni.dll
0x65d7e805: System_ni+0x0020e805
0x65d47843: System_ni+0x001d7843
0x65d477ef: System_ni+0x001d77ef
0x004700c9: +0x004700c9
0x67d73dd2: clr!CallDescrWorkerInternal+0x00000034
0x67d9cf6d: clr!CallDescrWorkerWithHandler+0x0000006b
0x67d9d267: clr!MethodDescCallSite::CallTargetWorker+0x00000152
0x67eb10e0: clr!RunMain+0x000001aa
0x67eb1200: clr!Assembly::ExecuteMainMethod+0x00000124
--------------------------------------
Handle = 0x0000024c - OPEN
Thread ID = 0x00001b58, Process ID = 0x00001bd4
0x77ad5704: ntdll!ZwCreateSemaphore+0x0000000c
0x75dcdcf9: KERNELBASE!CreateSemaphoreExW+0x0000005e
0x75f5e359: KERNEL32!CreateSemaphoreW+0x0000001d
0x65d7e805: System_ni+0x0020e805
0x65d47843: System_ni+0x001d7843
0x65d477ef: System_ni+0x001d77ef
0x004700c9: +0x004700c9
0x67d73dd2: clr!CallDescrWorkerInternal+0x00000034
0x67d9cf6d: clr!CallDescrWorkerWithHandler+0x0000006b
0x67d9d267: clr!MethodDescCallSite::CallTargetWorker+0x00000152
0x67eb10e0: clr!RunMain+0x000001aa
0x67eb1200: clr!Assembly::ExecuteMainMethod+0x00000124
...
--------------------------------------
Displayed 0xd stack traces for outstanding handles opened since the previous snapshot.
As you can see, the stack trace is missing my C# function names "Main" and "Fun1". I believe "System_ni+0x..." frames may be my function frames, but I don't know. My question is, how do I get WinDbg to display function names for my C# functions in the stack trace?
Extra information:
My WinDbg symbol search path is
SRVC:/symbolshttp://msdl.microsoft.com/download/symbols;D:\Projects\Sandpit\bin\Debug;srv*
I don't get any errors when I open the executable in WinDbg. There is a file called "Sandpit.pdb" in the output directory ("D:\Projects\Sandpit\bin\Debug"). The project is built locally so the pdb file should match the exe. I downloaded WinDbg from here. I have "Enable native code debugging" checked in the project settings in Visual Studio.
WinDbg attempts to interpret the native call stack as best it can, however to fully interpret the stack of a CLR application WinDbg needs to use an extension called SOS. This extension has a separate command CLRStack for viewing the stack information of CLR stacks. You will need to load the SOS extension first however using the .loadby sos clr command (or similar, I remember getting the correct version SOS to load could be a bit of a pain)
For more information see
WinDbg 101–A step by step guide to finding a simple memory leak in your .Net application
WinDbg / SOS Cheat Sheet
I'm trying to use a C++ DLL (3rd party library implementing EMI protocol, having source code available) in .NET. I've succesfully done marshalling, calling the functions and getting everything work fine.
The problem occurs when I want to do marshalling from IntPtr back into the .NET Struct , here's the code (modified as suggested - removed "ref" and changed the AllocHGlobal to allocate just size of emiStruct) :
private EMI emiStruct;
private IntPtr emiIntPtr;
emiIntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(emiStruct));
Marshal.StructureToPtr(emiStruct, emiIntPtr, false);
EMIStruct.Error result = emi_init(emiIntPtr, hostname, portNumber, password, shortNumber, windowSize, throughput);
Marshal.PtrToStructure(emiIntPtr, emiStruct);
The last line (PtrToStructure) causes an exception "Attempted to read or write protected memory. This is often an indication that other memory is corrupt".
Also, I can see a debug output:
A first chance exception of type 'System.AccessViolationException' occurred in mscorlib.dll
First-chance exception at 0x7c970441 in XXXXX.exe: 0xC0000005: Access violation reading location 0xc3fffff8.
First-chance exception at 0x7c970441 in XXXXX.exe: 0xC0000005: Access violation reading location 0x01fffff7.
First-chance exception at 0x7c970441 in XXXXX.exe: 0xC0000005: Access violation reading location 0x00001f1d.
I assume the problem is somewhere in allocation of memory for the pointer emiIntPtr. Althought, when I run the code, and there is a problem with connecting to the server (e.g. server not found), the followed marshalling to the Struct emiStruct is done correctly (no exception). The problem only occurs when the connection is succesfully established and server send a respond.
Also, I wrote a C++ sample app using the same DLL library I'm trying to use in .NET, and this application (when I compile it) runs just fine - it means, the C++ DLL should be ok and not causing crashing.
Furthermore, I've found some hints to check/uncheck several properties for the project compilator (using JIT, compile it for x86 cpu, etc.), unfortunately, none of this helped.
Do you have any suggestion where the problem might be or how to do a correct IntPtr inicialization in .NET and mapping between IntPtr and Struct?
Thanks all for your replies:
Here I'm adding the C++ header of the emi_init func:
FUNC( init)( EMI* emi, /* out */
const char* hostname, /* in */
unsigned short port, /* in */
const char* password, /* in */
const char* origin_addr, /* in */
int window_sz, /* in */
int throughput); /* in */
And here is the C# emi_init declaration (I've removed the "ref" attribute for emiPtr as was suggested):
[System.Runtime.InteropServices.DllImport("emi.dll", EntryPoint = "_emi_init")]
public static extern EMIStruct.Error emi_init(
System.IntPtr emiPtr,
[System.Runtime.InteropServices.InAttribute()] [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] string hostname,
ushort port,
[System.Runtime.InteropServices.InAttribute()] [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] string password,
[System.Runtime.InteropServices.InAttribute()] [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPStr)] string origin_addr,
int window_sz, int throughput);
However, still getting the same exception.
You are using Marshal.PtrToStructure incorrectly.
The second argument requires a type, iow typeof(EMI).
The return value contains the resulting struct.
So the solution should be:
var s = (EMI) Marshal.PtrToStructure(emiIntPtr, typeof(EMI));
My guess is that you have declared the first parameter incorrectly in the C#. You have declared it as ref IntPtr which is equivalent to EMI** in C++. But I bet the C++ declaration, which you unfortunately did not include, reads EMI*. So simply remove the ref and all should be well.
I expect that emi_init does not read from the EMI parameter, i.e. it has out semantics. In which case you don't need the StructureToPtr call before you call emi_init.
after running the .exe thought WinDBG, this was the exception information provided by pressing "k" when the exception occured:
ChildEBP RetAddr
0012e2f4 6f9fbb1c KERNELBASE!RaiseException+0x58
0012e354 6fba88f4 mscorwks!RaiseTheExceptionInternalOnly+0x2a8
0012e36c 6fba8966 mscorwks!RaiseTheException+0x4e
0012e394 6fba8997 mscorwks!RaiseTheException+0xc0
0012e3c0 6fba89a5 mscorwks!RealCOMPlusThrow+0x30
0012e3d0 6fac7ffe mscorwks!RealCOMPlusThrow+0xd
0012e8c8 6fa9d308 mscorwks!MethodTable::DoRunClassInitThrowing+0x44c
0012e914 6f9f8b9b mscorwks!DomainFile::Activate+0x226
0012e920 6f9cc537 mscorwks!DomainFile::DoIncrementalLoad+0xb4
0012e9a4 6f9cc43e mscorwks!AppDomain::TryIncrementalLoad+0x97
0012e9f4 6f9cd449 mscorwks!AppDomain::LoadDomainFile+0x19d
0012ea6c 6fb40e1a mscorwks!AppDomain::LoadDomainAssembly+0x116
0012eab0 6fb148c4 mscorwks!AppDomain::LoadExplicitAssembly+0x43
0012ed24 6fb167be mscorwks!ExecuteDLLForAttach+0x109
0012edd4 6fb16e9b mscorwks!ExecuteDLL+0x197
0012ee20 704c71f8 mscorwks!CorDllMainForThunk+0x8d
0012ee38 704ca1fe MSCOREE!CorDllMainWorkerForThunk+0x50
0012ee48 704bb2dc MSCOREE!VTableBootstrapThunkInitHelper+0x1b
0012eec8 7726519a MSCOREE!VTableBootstrapThunkInitHelperStub+0xc
WARNING: Stack unwind information not available. Following frames may be wrong.
0012eed0 7726517e ntdll!RtlpNtMakeTemporaryKey+0x43d6
0012eed4 770116fc ntdll!RtlpNtMakeTemporaryKey+0x43ba
0012ef10 77227d96 RPCRT4!DG_CCALL::DispatchPacket+0x1e3
0012ef14 014b1628 ntdll!RtlTimeToElapsedTimeFields+0xe902
0012ef18 00000000 0x14b1628
Does anyone knows what does this mean? And how can I solve it?
If it is a 3.5 or lower .NET then you have to load sos by calling ".loadby sos mscorwks". If it is a 4.0 then you have to use ".loadby sos clr".
What you're seeing is the unmanaged stack that's handling a managed exception. I suggest you do the following:
.load sos
!CLRStack
The first line will load SOS.dll, which allows for debugging of managed code. The second will print the managed stack trace. You can also use !help to see what other commands are available. For more information, see this MSDN article: http://msdn.microsoft.com/en-us/library/yy6d2sxs.aspx.