April 17, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Specifying Managed Arrays as Function Parameters in C++

  • July 12, 2004
  • By Tom Archer
  • Send Email »
  • More Articles »
Welcome to this week's installment of .NET Tips & Techniques! Each week, award-winning Architect and Lead Programmer Tom Archer from the Archer Consulting Group demonstrates how to perform a practical .NET programming task.

If you've been developing applications using the .NET Managed Extensions to C++, you've no doubt run into the peculiar syntax regarding defining arrays as input and output parameters to and from functions. To refresh your memory, look at some examples of defining functions that receive and return arrays.

The Standard Way

Here's an example of a function that takes an array of reference types (String objects):

// Function that takes an array of reference types
void PassArrayOfReferenceTypes(String* strings[])
{
}

// calling code
String* ar1[] = new String*[5];
PassArrayOfReferenceTypes(ar1);
Note that the type precedes the variable name with square brackets appended to the variable name. The number of dimensions is then specified by inserting commas between the brackets—one comma for two dimensions, two commas for three dimensions, and so on.

Now, look at the syntax involved in passing an array of value types (int) to a function:

// Function that takes an array of value types
void PassArrayOfValueTypes(int numbers __gc[])
{
}

// calling code
int ar2 __gc[] = new int __gc[5];
PassArrayOfValueTypes(ar2);
Take special note of the insertion of the __gc keyword. The reason for this is that while the array members are value types, the array itself is a reference type. Hence, the need for the __gc keyword.

Finally, let's look at how to define a function that returns an array. In native (non-.NET) C++, arrays are returned from a function to the caller via a pointer to the array's first element. With Managed Extensions, the array type and dimensions are both specified in the function's signature. The following example function illustrates a function that returns a two-dimensional array of int value objects:

int ReturnArray() [,]
{
  int values[,] = new int __gc [2,4]; // 2x4 array

  ...

  return values;
}

// calling code
int ar3 [,] = ReturnArray();
Note that the type precedes the function name and the brackets (indicating an array of that type) follows the closing parenthesis of the functions argument list. Commas are then used within the brackets to indicate the number of dimensions the array will contain.





Page 1 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel