C++/CLI supports managed arrays using a far more intuitive syntax than which existed in the older syntax. Here are some of the basic features of managed arrays in C++/CLI :-
- Syntax resembles that of C++ templates
System::Arrayis abstract base type for all managed arrays- Allocated on the CLR heap (means they get GC’d)
- Rank of the array need not be 1
- Implicit conversion to and explicit conversion from
System::Array - The rank and dimensions of an array object cannot be changed
Pseudo-template of an array type
The declaration and usage of array types in C++/CLI seems to use an imaginary template type (there is no such template of course, it’s all VC++ compiler magic)
namespace stdcli::language
{
template<typename T, int rank = 1>
ref class array : System::Array {};
}
Sample array usage
These samples show some code snippets that demo how to use single-dimensional and multi-dimensional arrays with C++/CLI
ref class R
{
public:
// Single dim array of ref type
void funcsdref()
{
array<String^>^ strarray =
gcnew array<String^>(5);
for(int i=0; i<5; i++)
strarray[i] = String::Concat("Str ",i.ToString());
for(int i=0; i<5; i++)
Console::WriteLine(strarray[i]);
}
//Single dim array of value type
void funcsdval()
{
array<int>^ strarray = gcnew array<int>(5);
for(int i=0; i<5; i++)
strarray[i] = i * 10;
for(int i=0; i<5; i++)
Console::WriteLine(strarray[i]);
}
//Multi dim array of ref type
void funcmdref()
{
array<String^,2>^ cricketerarray =
gcnew array<String^,2>(3,2);
cricketerarray[0,0] = "Sachin Tendulkar";
cricketerarray[0,1] = "India";
cricketerarray[1,0] = "Shane Warne";
cricketerarray[1,1] = "Australia";
cricketerarray[2,0] = "Shoaib Akhthar";
cricketerarray[2,1] = "Pakistan";
Console::WriteLine("Player\t\tCountry");
Console::WriteLine("-----------------------------");
for(int i=0; i<3; i++)
{
for(int j=0; j<2; j++)
Console::Write("{0} \t",cricketerarray[i,j]);
Console::WriteLine();
}
}
};
Jagged arrays
C++/CLI makes it really easy to declare and use jagged arrays. See my earlier blog entry for the syntax :-
Wondering whether I should expand on this blog entry and write an article on managed arrays π
Blog entries are cool for that. Like, when you think of writing an article, it seems a big task, but then make a blog entry or two on a particular subject and suddenly you find that you have just about 60-70% of required material for the article.