Aracılığıyla paylaş


Marshaling Different Types of Arrays

This sample demonstrates how to pass the following types of arrays:

  • Array of integers by value.

  • Array of integers by reference, which can be resized.

  • Multidimensional array (matrix) of integers by value.

  • Array of strings by value.

  • Array of structures with integers.

  • Array of structures with strings.

Unless an array is explicitly marshaled by reference, the default behavior marshals the array as an In parameter. You can change this behavior by applying the InAttribute and OutAttribute attributes explicitly.

The Arrays sample uses the following unmanaged functions, shown with their original function declaration:

  • TestArrayOfInts exported from PinvokeLib.dll.

    int TestArrayOfInts(int* pArray, int pSize);
    
  • TestRefArrayOfInts exported from PinvokeLib.dll.

    int TestRefArrayOfInts(int** ppArray, int* pSize);
    
  • TestMatrixOfInts exported from PinvokeLib.dll.

    int TestMatrixOfInts(int pMatrix[][COL_DIM], int row);
    
  • TestArrayOfStrings exported from PinvokeLib.dll.

    int TestArrayOfStrings(char** ppStrArray, int size);
    
  • TestArrayOfStructs exported from PinvokeLib.dll.

    int TestArrayOfStructs(MYPOINT* pPointArray, int size);
    
  • TestArrayOfStructs2 exported from PinvokeLib.dll.

    int TestArrayOfStructs2 (MYPERSON* pPersonArray, int size);
    

PinvokeLib.dll is a custom unmanaged library that contains implementations for the previously listed functions and two structure variables, MYPOINT and MYPERSON. The structures contain the following elements:

typedef struct _MYPOINT
{
   int x; 
   int y; 
} MYPOINT;

typedef struct _MYPERSON
{
   char* first; 
   char* last; 
} MYPERSON;

In this sample, the MyPoint and MyPerson structures contain embedded types. The StructLayoutAttribute attribute is set to ensure that the members are arranged in memory sequentially, in the order in which they appear.

The LibWrap class contains a set of methods called by the App class. For specific details about passing arrays, see the comments in the following sample. An array, which is a reference type, is passed as an In parameter by default. For the caller to receive the results, InAttribute and OutAttribute must be applied explicitly to the argument containing the array.

See Also

Concepts

Marshaling Arrays of Types

Platform Invoke Data Types

Creating Prototypes in Managed Code