Thursday, July 24, 2008

C++/CLI Gotchas

C++/CLI is a hybrid monster. I am very green in the world of C++/CLI. Below are a few very stupid problems I have met.

Example 1: If you are writing unsafe code in C++/CLI with mixed managed code and unmanaged code, it proved to be more dangerous than plain old C++. Here are a few examples of using System::String together with char (C native data type). Without thorough understanding of the new .NET String class will create code that compiles perfectly but return unexpected results to you in run time.

String^ str = "";
char ch = 'a';
str += ch; //result: str="97", instead of "a", because it called ch.ToString()
str = gcnew String(&ch); //result: str="a@#!$%", because &ch is considered to be a string
str = gcnew String(&ch, 0, 1); //result: str="a" as expected.


Example 2: Visual Studio 2005 Debugger is a liar

int i;
i=1000;
... //all the code in between so that you forgot what is defined
for(int i=0; i < 3; i++)
{
...
}
int k = i++; //if you set a break here, Visual Studio Debugger will tell you i=4??!

I agree that the code above is stupid which is an artifact from trying to correct old VC++ code. But Debugger giving a wrong answer wouldn't help!

No comments: