Saturday, August 30, 2014

Marshalling an Array of struct from DispInterface C++ COM to a C# Client

Hello Peter,


1. The return value from the method of the COM server, the VARIANT, translates to a C# object.


2. Now this object contains an array of objects (this is so since the return VARIANT is a SAFEARRAY of DispInterfaces).


3. What you have to do is to convert each of these array object element into the appropriate class (defined in the relevant interop assembly).


4. The following is an example :



static void DoTest()
{
// Suppose that the class which returns the VARIANT is
// called ArrayContainerClass.
ArrayContainerClass container = new ArrayContainerClass();

// Get it to return the SAFEARRAY of DispInterfaces.
// This SAFEARRAY is contained in a VARIANT and is
// represented as an object in C#.
object obj = container.GetArrayOfElements();

// Each array element is itself an object.
object[] obj_array = (object[])obj;

// Create an array of the elements of the array.
// Let's say each element is of type ArrayElementClass.
ArrayElementClass[] element_array = new ArrayElementClass[obj_array.Length];

// Convert each object element in obj_array into an ArrayElementClass instance.
for (int i = 0; i < obj_array.Length; i++)
{
element_array[i] = (ArrayElementClass)(Marshal.CreateWrapperOfType(obj_array[i], typeof(ArrayElementClass)));
}
}



- Bio.





Please visit my blog : http://ift.tt/1r6KxsJ


No comments:

Post a Comment