Sunday, 6 February 2011

Recent adventures with C++

Its been sometime since I've seriously worked with native interop and I can say I don’t really miss some of the joys in doing so. Here’s a problem that took us a better part of the day to figure out

Windows std::string are not backward compatible between 2010 and 2005.

It all started when i got asked to help debug a really weird issue involving some interop code from .net to c++. The problem manifested as memory violation crash in a simple call to a method accepting an std::string.

First we suspected that we didn't marshal the .net string to an std::string properly but after some digging and other attempt we discovered that was not it.

So we started to trim and trim down the code trying to achieve the minimal example that will recreate the crash. and while doing so we noticed that it doesn’t behave consistently.

The funkiest point was when we found out that when using short strings (under 16 bytes) everything seemed to work fine, but when the string got bigger than that it started to crash again.

To cut a short story short after a day (and some) we located the problem to be an inconsistent implementation of std::string class in a way that caused software that is compiled under 2010 in Release mode (only) not to work against dll compiled in VS 2005.

Working in debug or using the same development environment didn’t result in such a crash.

As i said Joy.


the 16 byte seem to be some inner optimization that std does in order to work faster with short strings.


Len Holgate said...

So the DLL used a std::string in its public interface?

That's your problem, by doing that you're restricting the dll to use by callers who are using the same implementation of std::string AND are compiled exactly the same as your dll.

See for more details.

Lior Friedman: said...

Yes and you are right.
However the damage is already done. The cost of changing that seems to be much to big Vs just working on the same environment.

In any case I really liked your post.
thought me something new, thank you.

Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Walgreens Printable Coupons