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;
... //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!

Monday, July 07, 2008

C++/CLI Warning C4945

Reason: This warning was generated because I referenced multiple C# projects in the C++/CLI project, and they all have "copy local" set to true.

Solution: Change reference to the C# projects, set all "copy local ..." properties to false.

A hotfix is available, which does not seem to be in SP1 as of 7/7/2008. So this fix probably will never be publicly available. This proves again C++/CLI is not on the top of TODO list for Visual Studio team.

Microsoft KB 922271: