ExecutionEngineException problem

I'm calling into an unmanaged DLL which takes a particular structure as input and returns another instance of that structure.  Both structures have pointers to buffers.  Those buffers in the input structure are expected to be allocated by the caller and the buffers in the return structure are allocated by the callee.  In both cases the caller is expected to do the deallocation.  I'm using Marshal.AllocHGlobal() in my C# code to allocate the buffers in the input structure.  Originally I thought I could use Marshal.FreeGlobal() to free both the buffers allocated in C# and the ones allocated by the callee but I got very strange errors.  Changing tactics, I wrote a Free() routine in the DLL and passed both structures to it and then did a GlobalFree() on the buffers in the DLL.  This seems to work until I shut down the app at which point I get an ExecutionEngineException error.  If I skip deallocating the memory, the error goes away so I'm assuming that the Framework keeps track of pointers allocated with Marshal.AllocHGlobal() and tries to free them up at shut down at which point things go haywire because they've already been freed.

Is there any good solution to this problem   I suppose I could probably request the DLL to allocate the buffers for me but this is a bit of a pain since there are several buffers with differing sizing requirements.  Also, it just feels like a big hack to ask the DLL to do something that the Framework is supposed to be able to do for me.  Alternatively, I could keep track of whether a particular structure has had its memory allocated by C# or by the callee and deallocate differently for the two different value types but - yuck!

Any suggestions/commisserations on this particular problem   Is this a problem with the Framework or should I be unsurprised by such behavior   The docs claim that I should never see ExecutionEngineException errors, but when using unmanaged code that doesn't seem wildly surprising if buffers are overwritten but that doesn't seem to be the case here.

Darrell


Answer this question

ExecutionEngineException problem

  • ExecutionEngineException problem