Enterprise Architect: Beware of for-each loops!


While developing a C#-based add-in for Sparx Enterprise Architect, I just encountered a very nasty bug:

System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at VariantClear(tagVARIANT* pvarg)
at System.Runtime.InteropServices.CustomMarshalers
.EnumeratorViewOfEnumVariant.MoveNext()
at Foo.bar()

The exception only arises when I deploy the add-in as a compiled (Release build) DLL. When debugging the add-in from within Visual Studio, it worked fine. And this is the “evil” code in Foo.bar():

foreach (EA.Element element in package.Elements)
{
    doSomething();
}

A second glance to the exception stack trace and a reading of this thread made me clear that the translation of “foreach” to a COM operation fails in that specific case. Use the following workaround to get rid of the issue:

for (short i = 0; i < package.Elements.Count; i++)
{
    EA.Element element =
        (EA.Element) package.Elements.GetAt(i);
    doSomething();
}

Much thanks to R Henry who had the same problem and posted his findings in the above-mentioned thread!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s