I know there is a few threads here that have been asked about the same subject but unfortunately non of them has helped me.
I am using a wrapper for unmanaged c++ code in my .net application, in the unmanaged Dll there’s a function “LoadLayoutFile()” where it loads a custom formatted file with extension (.lyt), my .net application has a loop where it calls that function based on array items count. If this array has one item, the application run smoothly without any problem, however if it had more than one item, the application crashes immediately without, of course, any chance to figure out what happened, but that also doesn’t happen all the time also, which is very much confusing.
I tried DebugDiag, Windbg to track the crash but I didn’t succeed with that.
I also tried to fix my unmanaged code by adding destructors, exception handling, I have also tried to put garbage collectors (in the .net application) where they should be, non of these have worked. I would love to know what’s going on? or at least to be able to catch an error!
Here’s LoadLayoutFile() in c++ dll:
int CMKCRD32App::LoadLayoutFile(LPCSTR lpszFileName)
{
try
{
int nRetVal = MCRC_SUCCESS;
CFile file;
WORD wVersionNumber;
// Add New Layout to the Layouts List
nRetVal = AddLayout();
// If Layout not added Correctly return Error Code
if(nRetVal<0)
return MCRC_MAXLAYOUT_REACHED;
if(file.Open(lpszFileName,CFile::modeRead|CFile::shareCompat))
{
CArchive ar(&file,CArchive::load);
ar >> wVersionNumber;
m_pCard[nRetVal]->Serialize(ar,wVersionNumber);
ar.Close();
file.Close();
m_pCard[nRetVal]->OffsetItemsByMargin(TRUE);
}
else
{
nRetVal = MCRC_ERROROPENFILE;
}
return nRetVal;
}
catch(char *str)
{
throw str;
}
}
The AddLayout()
int CMKCRD32App::AddLayout()
{
int nIndex;
try
{
for(nIndex=(_MAX_LAYOUTS_-1); nIndex >= 0; nIndex--)
if(m_pCard[nIndex]==NULL)
break;
if(nIndex>=0)
{
m_pCard[nIndex] = new CLYT_Card();
if(!m_pCard[nIndex])
{
nIndex = -1;
}
}
return nIndex;
}
catch(char *str)
{
throw str;
}
}
And here exactly where it crashes in .net application (sometimes):
CardLayout cardLayout = new CardLayout(); // Wrapper
foreach(var item in x)
int layout = cardLayout.LoadLayoutFile("cc.lyt");
Your library looks fine, may be it’s a performance thing, you may have a large stack trace. If it’s not crashing when you call it once and it does when you call it more than that (sometimes like you said) it could be because of huge objects in memory especially if your library has some image processing job to do (I’m assuming that because I have seen
layoutfile) and it doesn’t destroy them properly.My advice to you is to try to separate your desktop application code from the part that calls that library, may be you should try to let it work on another thread or try to put that code segment in a console application and call that console application from your desktop application, that will separate them from each other and if any crash may happen it will not affect your desktop application.