Specifying Managed Arrays as Function Parameters in C++
A More Intuitive Way
We're all professionals here and can learn to adapt to any new syntax that gets thrown our way. However, with just a couple of type definitions and a macro, we can make our code much more readable and intuitive. For example, instead of having to remember to use the __gc keyword with arrays of value type members, we can simply define a typedef for each desired type so that we can use the same syntax for either reference or value types. From there, we can specify a generic macro that takes the type name as a parameter so we don't have to remember the name of the typedef for each supported type. Here's how that would look:#define MCArray(type) type##Array typedef int intArray __gc[]; typedef String* StringArray []; // .. add more typedefs here per your needs
Now, compare the following function signatures, standard Managed Extensions syntax vs. the MCArray macro:
// Returning arrays using the Standard Managed Extensions syntax int ReturnInt1() __gc[] String* ReturnString1() [] // Returning arrays using the MCArray macro MCArray(int) ReturnInt2() MCArray(String) ReturnString2() // Passing arrays using the Standard Managed Extensions syntax void PassArrayOfReferenceTypes(String* strings[]) void PassArrayOfValueTypes(int numbers __gc[]) // Passing arrays using the MCArray macro void PassArrayOfReferenceTypes(MCArray(String) values) void PassArrayOfValueTypes(MCArray(int) values)
As you can see, MCArray macro provides several benefits, including the following:
- You don't have to remember which types require the pointer specification.
- You don't have to remember which types require the __gc keyword.
- You don't have to remember to place the square brackets nor where to place them.
In summary, the MCArray is much closer to native C++ syntax, resulting in fewer mistakes and greater readability.
About the Author
The founder of the Archer Consulting Group (ACG), Tom Archer has been the project lead on three award-winning applications and is a best-selling author of 10 programming books as well as countless magazine and online articles.
Page 2 of 2
This article was originally published on July 12, 2004